@capacitor/local-notifications
本地通知 API 提供了一种在设备本地调度通知的方式(即无需服务器发送推送通知)。
安装
npm install @capacitor/local-notifications@latest-5
npx cap sync
Android 系统
Android 13 需要权限检查才能发送通知。您必须相应地调用 checkPermissions() 和 requestPermissions()。
在 Android 12 及更早版本上,不会显示权限提示,直接返回已授予状态。
从 Android 12 开始,除非在您的 AndroidManifest.xml 中添加此权限,否则计划通知将不精确:
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
请注意,即使存在该权限,用户仍然可以从应用设置中禁用精确通知。
配置
在 Android 上,本地通知可以使用以下选项进行配置:
| 属性 | 类型 | 描述 | 自版本 |
|---|---|---|---|
smallIcon | string | 设置通知的默认状态栏图标。图标应放置在应用的 res/drawable 文件夹中。此选项的值应为 drawable 资源 ID,即不带扩展名的文件名。仅适用于 Android。 | 1.0.0 |
iconColor | string | 设置通知状态栏图标的默认颜色。仅适用于 Android。 | 1.0.0 |
sound | string | 设置通知的默认提示音。在 Android 26+ 上,它设置默认通道的声音,除非卸载应用,否则无法更改。如果找不到音频文件,在 Android 21-25 上将播放默认系统声音,而在 Android 26+ 上将没有声音。仅适用于 Android。 | 1.0.0 |
示例
在 capacitor.config.json 中:
{
"plugins": {
"LocalNotifications": {
"smallIcon": "ic_stat_icon_config_sample",
"iconColor": "#488AFF",
"sound": "beep.wav"
}
}
}
在 capacitor.config.ts 中:
/// <reference types="@capacitor/local-notifications" />
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
plugins: {
LocalNotifications: {
smallIcon: "ic_stat_icon_config_sample",
iconColor: "#488AFF",
sound: "beep.wav",
},
},
};
export default config;
低电耗模式
如果设备已进入低电耗模式,您的应用功能可能会受到限制。如果您需要在低电耗模式下仍能触发通知,请通过设置 allowWhileIdle: true 来调度通知。请谨慎使用 allowWhileIdle,因为这些通知每个应用每 9 分钟只能触发一次。
API
schedule(...)getPending()registerActionTypes(...)cancel(...)areEnabled()getDeliveredNotifications()removeDeliveredNotifications(...)removeAllDeliveredNotifications()createChannel(...)deleteChannel(...)listChannels()checkPermissions()requestPermissions()addListener('localNotificationReceived', ...)addListener('localNotificationActionPerformed', ...)removeAllListeners()- 接口
- 类型别名
- 枚举
schedule(...)
schedule(options: ScheduleOptions) => Promise<ScheduleResult>
调度一个或多个本地通知。
| 参数 | 类型 |
|---|---|
options | |
返回值:
Promise<ScheduleResult>
自版本: 1.0.0
getPending()
getPending() => Promise<PendingResult>
获取待处理通知列表。
返回值:
Promise<PendingResult>
自版本: 1.0.0
registerActionTypes(...)
registerActionTypes(options: RegisterActionTypesOptions) => Promise<void>
注册显示通知时要执行的操作。
仅适用于 iOS 和 Android。
| 参数 | 类型 |
|---|---|
options | |
自版本: 1.0.0
cancel(...)
cancel(options: CancelOptions) => Promise<void>
取消待处理通知。
| 参数 | 类型 |
|---|---|
options | |
自版本: 1.0.0
areEnabled()
areEnabled() => Promise<EnabledResult>
检查通知功能是否已启用。
返回值:
Promise<EnabledResult>
自版本: 1.0.0
getDeliveredNotifications()
getDeliveredNotifications() => Promise<DeliveredNotifications>
获取通知屏幕上可见的通知列表。
返回值:
Promise<DeliveredNotifications>