跳到主要内容
版本:v7

@capacitor/local-notifications

Local Notifications API 提供了一种在本地安排设备通知的方式(即无需服务器发送推送通知)。

安装

npm install @capacitor/local-notifications@latest-7
npx cap sync

Android

Android 13 需要进行权限检查才能发送通知。你需要相应地调用 checkPermissions()requestPermissions()

在 Android 12 及更早版本上,不会显示提示,并会直接返回已授权。

从 Android 12 开始,除非将以下权限添加到你的 AndroidManifest.xml 中,否则计划的通知将不会精确执行:

<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />

请注意,即使该权限存在,用户仍然可以从应用设置中禁用精确通知。使用 checkExactNotificationSetting() 来检查该设置的值。如果用户禁用了此设置,应用将重新启动,并且任何使用精确闹钟计划的通知都将被删除。如果你的应用依赖于精确闹钟,请务必在应用启动时(例如,在 App.appStateChange 中)检查此设置,以便提供备用方案或替代行为。

在 Android 14 上,新增了一个名为 USE_EXACT_ALARM 的权限。使用此权限可以在无需向用户请求权限的情况下使用精确闹钟。仅当精确闹钟的使用对你的应用功能至关重要时才应使用此权限。在此处阅读有关使用此权限的影响的更多信息。

从 Android 15 开始,用户可以将应用安装在私人空间中。用户可以随时锁定其私人空间,这意味着在用户解锁之前不会显示推送通知。

无法检测应用是否安装在私人空间中。因此,如果你的应用显示任何关键通知,请告知你的用户避免将应用安装在私人空间中。

有关你的应用与私人空间相关的行为变更的更多信息,请参阅 Android 文档

配置

在 Android 上,本地通知可以通过以下选项进行配置:

属性类型描述自版本
smallIconstring设置通知的默认状态栏图标。图标应放置在应用的 res/drawable 文件夹中。此选项的值应为可绘制资源 ID,即不带扩展名的文件名。仅适用于 Android。1.0.0
iconColorstring设置通知状态栏图标的默认颜色。仅适用于 Android。1.0.0
soundstring设置通知的默认通知声音。在 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;

Doze 模式

如果设备已进入 Doze 模式,你的应用可能会受到功能限制。如果你需要通知即使在 Doze 模式下也能触发,请使用 allowWhileIdle: true 来安排通知。请谨慎使用 allowWhileIdle,因为这些通知每个应用每 9 分钟只能触发一次

API

schedule(...)

schedule(options: ScheduleOptions) => Promise<ScheduleResult>

安排一个或多个本地通知。

参数类型
options
ScheduleOptions

返回值:

Promise<ScheduleResult>

自版本: 1.0.0


getPending()

getPending() => Promise<PendingResult>

获取待处理通知的列表。

返回值:

Promise<PendingResult>

自版本: 1.0.0


registerActionTypes(...)

registerActionTypes(options: RegisterActionTypesOptions) => Promise<void>

注册通知显示时要执行的操作。

仅适用于 iOS 和 Android。

参数类型
options
RegisterActionTypesOptions

自版本: 1.0.0


cancel(...)

cancel(options: CancelOptions) => Promise<void>

取消待处理的通知。

参数类型
options
CancelOptions

自版本: 1.0.0


areEnabled()

areEnabled() => Promise<EnabledResult>

检查通知是否已启用。

返回值:

Promise<EnabledResult>

自版本: 1.0.0


getDeliveredNotifications()

getDeliveredNotifications() => Promise<DeliveredNotifications>

获取通知屏幕上可见的通知列表。

返回值:

Promise<DeliveredNotifications>

自版本: 4.0.0


removeDeliveredNotifications(...)

removeDeliveredNotifications(delivered: DeliveredNotifications) => Promise<void>

从通知屏幕中移除指定的通知。

参数类型
delivered
DeliveredNotifications

自版本: 4.0.0


removeAllDeliveredNotifications()

removeAllDeliveredNotifications() => Promise<void>

从通知屏幕中移除所有通知。

自版本: 4.0.0


createChannel(...)

createChannel(channel: Channel) => Promise<void>

创建通知频道。

仅适用于 Android。

参数类型
channel
Channel

自版本: 1.0.0


deleteChannel(...)

deleteChannel(args: { id: string; }) => Promise<void>

删除通知频道。

仅适用于 Android。

参数类型
args{ id: string; }

自版本: 1.0.0


listChannels()

listChannels() => Promise<ListChannelsResult>

获取通知频道列表。

仅适用于 Android。

返回值:

Promise<ListChannelsResult>

自版本: 1.0.0


checkPermissions()

checkPermissions() => Promise<PermissionStatus>

检查显示本地通知的权限。

返回值:

Promise<PermissionStatus>

自版本: 1.0.0


requestPermissions()

requestPermissions() => Promise<PermissionStatus>

请求显示本地通知的权限。

返回值:

Promise<PermissionStatus>

自版本: 1.0.0


changeExactNotificationSetting()

changeExactNotificationSetting() => Promise<SettingsPermissionStatus>

引导用户进入应用设置屏幕以配置精确闹钟。

如果用户将设置从已授权更改为拒绝,应用 将重新启动,并且任何使用精确闹钟计划的通知都将被删除。

在 Android < 12 上,用户将不会被引导到应用设置屏幕,此函数将 返回 granted

仅适用于 Android。

返回值:

Promise<SettingsPermissionStatus>

自版本: 6.0.0


checkExactNotificationSetting()

checkExactNotificationSetting() => Promise<SettingsPermissionStatus>

检查使用精确闹钟的应用设置。

仅适用于 Android。

返回值:

Promise<SettingsPermissionStatus>

自版本: 6.0.0


addListener('localNotificationReceived', ...)

addListener(eventName: 'localNotificationReceived', listenerFunc: (notification: LocalNotificationSchema) => void) => Promise<PluginListenerHandle>

监听通知显示时的事件。

参数类型
eventName'localNotificationReceived'
listenerFunc
(notification: LocalNotificationSchema) => void

返回值:

Promise<PluginListenerHandle>

自版本: 1.0.0


addListener('localNotificationActionPerformed', ...)

addListener(eventName: 'localNotificationActionPerformed', listenerFunc: (notificationAction: ActionPerformed) => void) => Promise<PluginListenerHandle>

监听通知上执行操作时的事件。

参数类型
eventName'localNotificationActionPerformed'
listenerFunc
(notificationAction: ActionPerformed) => void

返回值:

Promise<PluginListenerHandle>

自版本: 1.0.0


removeAllListeners()

removeAllListeners() => Promise<void>

移除此插件的所有监听器。

自版本: 1.0.0


接口

ScheduleResult

属性类型描述自版本
notificationsLocalNotificationDescriptor[]已安排的通知列表。1.0.0

LocalNotificationDescriptor

描述本地通知的对象。

属性类型描述自版本
idnumber通知标识符。1.0.0

ScheduleOptions

属性类型描述自版本
notificationsLocalNotificationSchema[]要安排的通知列表。1.0.0

LocalNotificationSchema

属性类型描述自版本
titlestring通知的标题。1.0.0
bodystring通知的正文,显示在标题下方。1.0.0
largeBodystring设置用于大文本通知样式显示的多行文本块。1.0.0
summaryTextstring用于设置收件箱和大文本通知样式中的摘要文本详细信息。仅适用于 Android。1.0.0
idnumber通知标识符。在 Android 上是一个 32 位整数,因此值应在 -2147483648 到 2147483647 之间(含边界)。1.0.0
schedule
Schedule
将通知安排在稍后的时间。1.0.0
soundstring显示此通知时要播放的音频文件名称。包含文件名及其扩展名。在 iOS 上,文件应在应用包中。在 Android 上,文件应在 res/raw 文件夹中。推荐使用 .wav 格式,因为 iOS 和 Android 都支持。仅适用于 iOS 和 Android < 26。对于 Android 26+,请使用配置了所需声音的 channelId。如果找不到声音文件(例如空字符串或错误的名称),将使用系统默认通知声音。如果未提供,在 Android 上会产生默认声音,在 iOS 上则没有声音。1.0.0
smallIconstring设置自定义状态栏图标。如果设置,此选项将覆盖 Capacitor 配置中的 smallIcon 选项。图标应放置在应用的 res/drawable 文件夹中。此选项的值应为可绘制资源 ID,即不带扩展名的文件名。仅适用于 Android。1.0.0
largeIconstring设置通知的大图标。图标应放置在应用的 res/drawable 文件夹中。此选项的值应为可绘制资源 ID,即不带扩展名的文件名。仅适用于 Android。1.0.0
iconColorstring设置通知图标的颜色。仅适用于 Android。1.0.0
attachmentsAttachment[]为此通知设置附件。1.0.0
actionTypeIdstring为此通知关联一个操作类型。1.0.0
extraany设置要存储在此通知中的额外数据。1.0.0
threadIdentifierstring用于对多个通知进行分组。在 UNMutableNotificationContent 上设置 threadIdentifier。仅适用于 iOS。1.0.0
summaryArgumentstring此通知添加到类别摘要格式字符串的字符串。在 UNMutableNotificationContent 上设置 summaryArgument。仅适用于 iOS。1.0.0
groupstring用于对多个通知进行分组。使用提供的值在 NotificationCompat.Builder 上调用 setGroup()。仅适用于 Android。1.0.0
groupSummaryboolean如果为 true,此通知将成为一组通知的摘要。使用提供的值在 NotificationCompat.Builder 上调用 setGroupSummary()。仅在使用 group 时适用于 Android。1.0.0
channelIdstring指定通知应发送到的频道。如果给定名称的频道不存在,则通知将不会触发。如果未提供,将使用默认频道。使用提供的值在 NotificationCompat.Builder 上调用 setChannelId()。仅适用于 Android 26+。1.0.0
ongoingboolean如果为 true,通知将无法滑动清除。使用提供的值在 NotificationCompat.Builder 上调用 setOngoing()。仅适用于 Android。1.0.0
autoCancelboolean如果为 true,用户点击通知时通知将被取消。使用提供的值在 NotificationCompat.Builder 上调用 setAutoCancel()。仅适用于 Android。1.0.0
inboxListstring[]设置用于收件箱样式通知显示的字符串列表。最多允许 5 个字符串。仅适用于 Android。1.0.0
silentboolean如果为 true,应用在前台时通知将不会出现。仅适用于 iOS。5.0.0

Schedule

表示通知的计划。

使用 atonevery 来安排通知。

属性类型描述自版本
at
Date
在特定日期和时间安排通知。1.0.0
repeatsbooleanat 指定的日期和时间重复投递此通知。仅适用于 iOS 和 Android。1.0.0
allowWhileIdleboolean允许此通知在 Doze 模式下触发。仅适用于 Android 23+。请注意,这些通知每个应用每 9 分钟只能触发一次1.0.0
on
ScheduleOn
在特定时间间隔安排通知。这类似于安排 cron 任务。仅适用于 iOS 和 Android。1.0.0
every
ScheduleEvery
按特定时间间隔安排通知。1.0.0
countnumber限制由 every 指定的时间间隔投递通知的次数。1.0.0

Date

支持日期和时间的基本存储和检索。

方法签名描述
toString() => string返回日期的字符串表示。格式取决于区域设置。
toDateString() => string以字符串值返回日期。
toTimeString() => string以字符串值返回时间。
toLocaleString() => string返回适合宿主环境当前区域设置的字符串值。
toLocaleDateString() => string返回适合宿主环境当前区域设置的日期字符串值。
toLocaleTimeString() => string返回适合宿主环境当前区域设置的时间字符串值。
valueOf() => number返回自 1970 年 1 月 1 日 00:00:00 UTC 以来存储的时间值(毫秒)。
getTime() => number获取时间值(毫秒)。
getFullYear() => number使用本地时间获取年份。
getUTCFullYear() => number使用协调世界时(UTC)获取年份。
getMonth() => number使用本地时间获取月份。
getUTCMonth() => number使用协调世界时(UTC)获取 Date 对象的月份。
getDate() => number使用本地时间获取月份中的日期。
getUTCDate() => number使用协调世界时(UTC)获取月份中的日期。
getDay() => number使用本地时间获取星期几。
getUTCDay() => number使用协调世界时(UTC)获取星期几。
getHours() => number使用本地时间获取日期中的小时。
getUTCHours() => number使用协调世界时(UTC)获取 Date 对象中的小时值。
getMinutes() => number使用本地时间获取 Date 对象的分钟。
getUTCMinutes() => number使用协调世界时(UTC)获取 Date 对象的分钟。
getSeconds() => number使用本地时间获取 Date 对象的秒数。
getUTCSeconds() => number使用协调世界时(UTC)获取 Date 对象的秒数。
getMilliseconds() => number使用本地时间获取 Date 的毫秒数。
getUTCMilliseconds() => number使用协调世界时(UTC)获取 Date 对象的毫秒数。
getTimezoneOffset() => number获取本地计算机时间与协调世界时(UTC)之间的分钟差。
setTime(time: number) => number设置 Date 对象中的日期和时间值。
setMilliseconds(ms: number) => number使用本地时间设置 Date 对象中的毫秒值。
setUTCMilliseconds(ms: number) => number使用协调世界时(UTC)设置 Date 对象中的毫秒值。
setSeconds(sec: number, ms?: number | undefined) => number使用本地时间设置 Date 对象中的秒值。
setUTCSeconds(sec: number, ms?: number | undefined) => number使用协调世界时(UTC)设置 Date 对象中的秒值。
setMinutes(min: number, sec?: number | undefined, ms?: number | undefined) => number使用本地时间设置 Date 对象中的分钟值。
setUTCMinutes(min: number, sec?: number | undefined, ms?: number | undefined) => number使用协调世界时(UTC)设置 Date 对象中的分钟值。
setHours(hours: number, min?: number | undefined, sec?: number | undefined, ms?: number | undefined) => number使用本地时间设置 Date 对象中的小时值。
setUTCHours(hours: number, min?: number | undefined, sec?: number | undefined, ms?: number | undefined) => number使用协调世界时(UTC)设置 Date 对象中的小时值。
setDate(date: number) => number使用本地时间设置 Date 对象中月份的第几天数值。
setUTCDate(date: number) => number使用协调世界时(UTC)设置 Date 对象中月份的第几天数值。
setMonth(month: number, date?: number | undefined) => number使用本地时间设置 Date 对象中的月份值。
setUTCMonth(month: number, date?: number | undefined) => number使用协调世界时(UTC)设置 Date 对象中的月份值。
setFullYear(year: number, month?: number | undefined, date?: number | undefined) => number使用本地时间设置 Date 对象的年份。
setUTCFullYear(year: number, month?: number | undefined, date?: number | undefined) => number使用协调世界时(UTC)设置 Date 对象中的年份值。
toUTCString() => string使用协调世界时(UTC)将日期转换为字符串。
toISOString() => string以 ISO 格式将日期作为字符串值返回。
toJSON(key?: any) => string由 JSON.stringify 方法使用,以实现对象数据到 JavaScript 对象表示法(JSON)序列化的转换。

ScheduleOn

属性类型
yearnumber
monthnumber
daynumber
weekday
Weekday
hournumber
minutenumber
secondnumber

Attachment

表示通知附件。

属性类型描述自版本
idstring附件标识符。1.0.0
urlstring附件的 URL。使用 res 方案引用 Web 资源,例如 res:///assets/img/icon.png。也接受 file URL。1.0.0
options
AttachmentOptions
附件选项。1.0.0

AttachmentOptions

属性类型描述自版本
iosUNNotificationAttachmentOptionsTypeHintKeystringUNNotificationAttachment 的可散列选项中设置 UNNotificationAttachmentOptionsTypeHintKey 键。仅适用于 iOS。1.0.0
iosUNNotificationAttachmentOptionsThumbnailHiddenKeystringUNNotificationAttachment 的可散列选项中设置 UNNotificationAttachmentOptionsThumbnailHiddenKey 键。仅适用于 iOS。1.0.0
iosUNNotificationAttachmentOptionsThumbnailClippingRectKeystringUNNotificationAttachment 的可散列选项中设置 UNNotificationAttachmentOptionsThumbnailClippingRectKey 键。仅适用于 iOS。1.0.0
iosUNNotificationAttachmentOptionsThumbnailTimeKeystringUNNotificationAttachment 的可散列选项中设置 UNNotificationAttachmentOptionsThumbnailTimeKey 键。仅适用于 iOS。1.0.0

PendingResult

属性类型描述自版本
notificationsPendingLocalNotificationSchema[]待处理的通知列表。1.0.0

PendingLocalNotificationSchema

属性类型描述自版本
titlestring通知的标题。1.0.0
bodystring通知的正文,显示在标题下方。1.0.0
idnumber通知标识符。1.0.0
schedule
Schedule
将通知安排在稍后的时间。1.0.0
extraany设置要存储在此通知中的额外数据。1.0.0

RegisterActionTypesOptions

属性类型描述自版本
typesActionType[]要注册的操作类型列表。1.0.0

ActionType

操作的集合。

属性类型描述自版本
idstring操作类型的 ID。在通知中通过 actionTypeId 键引用。1.0.0
actionsAction[]与此操作类型关联的操作列表。1.0.0
iosHiddenPreviewsBodyPlaceholderstring设置 UNNotificationCategoryhiddenPreviewsBodyPlaceholder。仅适用于 iOS。1.0.0
iosCustomDismissActionbooleanUNNotificationCategory 的选项中设置 customDismissAction。仅适用于 iOS。1.0.0
iosAllowInCarPlaybooleanUNNotificationCategory 的选项中设置 allowInCarPlay。仅适用于 iOS。1.0.0
iosHiddenPreviewsShowTitlebooleanUNNotificationCategory 的选项中设置 hiddenPreviewsShowTitle。仅适用于 iOS。1.0.0
iosHiddenPreviewsShowSubtitlebooleanUNNotificationCategory 的选项中设置 hiddenPreviewsShowSubtitle。仅适用于 iOS。1.0.0

Action

通知显示时可以执行的操作。

属性类型描述自版本
idstring操作标识符。在 'actionPerformed' 事件中作为 actionId 引用。1.0.0
titlestring为此操作显示的标题文本。1.0.0
requiresAuthenticationbooleanUNNotificationAction 的选项中设置 authenticationRequired。仅适用于 iOS。1.0.0
foregroundbooleanUNNotificationAction 的选项中设置 foreground。仅适用于 iOS。1.0.0
destructivebooleanUNNotificationAction 的选项中设置 destructive。仅适用于 iOS。1.0.0
inputboolean使用 UNTextInputNotificationAction 而不是 UNNotificationAction。仅适用于 iOS。1.0.0
inputButtonTitlestringUNTextInputNotificationAction 上设置 textInputButtonTitle。仅当 inputtrue 时适用于 iOS。1.0.0
inputPlaceholderstringUNTextInputNotificationAction 上设置 textInputPlaceholder。仅当 inputtrue 时适用于 iOS。1.0.0

CancelOptions

属性类型描述自版本
notificationsLocalNotificationDescriptor[]要取消的通知列表。1.0.0

EnabledResult

属性类型描述自版本
valueboolean设备是否已启用本地通知。1.0.0

DeliveredNotifications

属性类型描述自版本
notificationsDeliveredNotificationSchema[]通知屏幕上可见的通知列表。1.0.0

DeliveredNotificationSchema

属性类型描述自版本
idnumber通知标识符。4.0.0
tagstring通知标签。仅适用于 Android。4.0.0
titlestring通知的标题。4.0.0
bodystring通知的正文,显示在标题下方。4.0.0
groupstring通知的已配置分组。仅适用于 Android。4.0.0
groupSummaryboolean此通知是否为一组通知的摘要。仅适用于 Android。4.0.0
dataany通知负载中包含的任何额外数据。仅适用于 Android。4.0.0
extraany要存储在此通知中的额外数据。仅适用于 iOS。4.0.0
attachmentsAttachment[]此通知的附件。仅适用于 iOS。1.0.0
actionTypeIdstring与此通知关联的操作类型。仅适用于 iOS。4.0.0
schedule
Schedule
用于触发此通知的计划。仅适用于 iOS。4.0.0
soundstring通知显示时使用的声音。仅适用于 iOS。4.0.0

Channel

属性类型描述默认值自版本
idstring频道标识符。1.0.0
namestring此频道的人类可读名称(向用户显示)。1.0.0
descriptionstring此频道的描述(向用户显示)。1.0.0
soundstring发布到此频道的通知应播放的声音。重要性至少为 3 的通知频道应有声音。声音文件的文件名应相对于 Android 应用的 res/raw 目录指定。如果未提供声音或找不到声音文件,将不会使用任何声音。1.0.0
importance
Importance
发布到此频道的通知的中断级别。
3
1.0.0
visibility
Visibility
发布到此频道的通知的可见性。此设置用于控制发布到此频道的通知是否出现在锁屏上,以及如果出现,是否以编辑形式显示。1.0.0
lightsboolean发布到此频道的通知是否应在支持该功能的设备上显示通知灯。1.0.0
lightColorstring发布到此频道的通知的灯光颜色。仅当此频道启用了灯光且设备支持时才有效。支持的颜色格式为 #RRGGBB#RRGGBBAA1.0.0
vibrationboolean发布到此频道的通知是否应振动。1.0.0

ListChannelsResult

属性类型描述自版本
channelsChannel[]通知频道的列表。1.0.0

PermissionStatus

属性类型描述自版本
display
PermissionState
显示通知的权限状态。1.0.0

SettingsPermissionStatus

属性类型描述自版本
exact_alarm
PermissionState
使用精确闹钟的权限状态。6.0.0

PluginListenerHandle

属性类型
remove() => Promise<void>

ActionPerformed

属性类型描述自版本
actionIdstring执行的操作的标识符。1.0.0
inputValuestring用户在通知中输入的值。仅适用于 input 设置为 true 的 iOS 通知。1.0.0
notification
LocalNotificationSchema
原始通知 schema。1.0.0

类型别名

ScheduleEvery

'year' | 'month' | 'two-weeks' | 'week' | 'day' | 'hour' | 'minute' | 'second'

Importance

重要性级别。更多详情,请参阅 Android 开发者文档

1 | 2 | 3 | 4 | 5

Visibility

通知可见性。更多详情,请参阅 Android 开发者文档

-1 | 0 | 1

PermissionState

'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'

枚举

Weekday

成员
Sunday1
Monday2
Tuesday3
Wednesday4
Thursday5
Friday6
Saturday7