Capacitor 插件 实现本地通知 Local Notification @capacitor/local-notifications

Capacitor 插件 实现本地通知 Local Notification @capacitor/local-notifications

在前一个文章中使用 Capacitor 和 H5 应用构建了一个 Android 应用,这个 h5 是通过 uniapp 生成的。

https://blog.csdn.net/KimBing/article/details/134093769

这个应用的构成是这样一个过程:

  1. 使用 uniapp 进行程序编写
  2. 生成 h5 最终文件
  3. 将 h5 移到 Capacitor 的框架中
  4. 使用 AndroidStudio 打开 Capacitor 构建的 Android 应用即可生成 Android APK

我们添加通知插件过程在第1个步骤中。在 uniapp 原文件中使用,跟在正常的 Vue 项目中使用 NPM 包是一样的。

一、uniapp 项目中添加 Capacitor 通知插件

首先你需要知道一点

npm install @capacitor/local-notifications

在你需要调用通知的页面中引入这个插件

  import { LocalNotifications } from '@capacitor/local-notifications';
<script>
	import alarmApi from "@/api/alarmApi";
    import util from "@/tools/util";
    import systemApi from "./api/systemApi";

    import { LocalNotifications } from '@capacitor/local-notifications';

    export default {
		onLaunch: function() {
            let token = uni.getStorageSync('token')
            if (!token){
                uni.reLaunch({url: '/pages/login/Login'})
            }
            this.getAbout()
        },
		onShow: function() {
			console.log('App Show')

二、发出一个本地通知

官方文档:https://capacitorjs.com/docs/apis/local-notifications#schedule

发通知是使用的 LocalNotifications.schedule({notifications: []}) 方法,具体的参数看官方文档

这个可以同时发出多个通知,它的参数是这样的:

LocalNotifications.schedule({
    notifications: [ 通知数组 ]
})

这个 通知数组 的结构是这样的

{
    title: '标题',
    body: '具体内容',
    id: 通知id, // 这个之后会用于筛选或者对通知进行操作
}

最终你发出的通知就是这样:
在这里插入图片描述
比如你需要发出一条 id 为 2 的通知,如果你没有在发通知之前进行判断,判断这条通知是否已经存在于已发起的通知列表中,它就会一直发通知
在这里插入图片描述

三、过滤已存在的通知

为了避免上面这个问题,就需要对将要发出的通知进行过滤。

比如你要发出的通知是你后台系统中的通知列表,这个列表中每个通知都有一个唯一的 id,我们就用这个 id 作为通知的 id。

 LocalNotifications.getDeliveredNotifications()
   .then(oldNotification => {
       console.log('old: ',oldNotification)
       let oldIds = oldNotification.notifications.map(item => item.id)
       LocalNotifications.schedule({
           notifications: notifications.filter(item => !oldIds.includes(item.id))
       })
})

这里 notification 数组中的内容是下面这样的

在这里插入图片描述

oldNotification 的结构是这样的:

{
	notifications: [通知数组]
}

四、这样就可以了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十月ooOO

许个愿,我帮你实现

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值