跳到主要内容
版本:v8

@capacitor/local-notifications

本地通知 API 提供了一种在本地调度设备通知的方法(即无需服务器发送推送通知)。

安装

npm install @capacitor/local-notifications
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 15 开始,应用可以安装在私密空间中。用户可以随时锁定其私密空间,这意味着在用户解锁之前不会显示推送通知。

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

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

配置

这些配置值可用:

PropTypeDescriptionDefaultSince
soundstring用于通知的声音文件的名称。该值必须不包含扩展名。default1.0.0
iconColorstring图标的十六进制颜色,格式为 #RRGGBB。仅适用于 Android。1.0.0
listOptionsobject获取通知时列表的选项。包含 limit(最大通知数)类型为 number5.0.0
notificationsobject[]应用启动时通知的默认设置。完整的选项列表可以在 LocalNotificationSchema 接口中找到。包含 title(通知标题)类型为 stringbody(通知正文)类型为 stringid(通知的唯一标识符)类型为 numbersound(通知的声音)类型为 stringschedule(通知的时间表信息)类型为 object1.0.0

示例

capacitor.config.json 中:

{
"plugins": {
"LocalNotifications": {
"sound": "beep.wav",
"iconColor": "#FF00FF",
"listOptions": {
"limit": 10
},
"notifications": [
{
"title": "Hey you",
"body": "This is a notification",
"id": 1,
"sound": "beep.wav",
"schedule": {
"at": new Date(new Date().getTime() + 60000)
}
}
]
}
}
}

capacitor.config.ts 中:

/// <reference types="@capacitor/local-notifications" />

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
plugins: {
LocalNotifications: {
sound: "beep.wav",
iconColor: "#FF00FF",
listOptions: {
limit: 10
},
notifications: [
{
title: "Hey you",
body: "This is a notification",
id: 1,
sound: "beep.wav",
schedule: {
at: new Date(new Date().getTime() + 60000)
}
}
]
},
},
};

export default config;

示例

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

const scheduleNotifs = async () => {
await LocalNotifications.schedule({
notifications: [
{
title: 'Title',
body: 'Body',
id: 1,
schedule: {
at: new Date(new Date().getTime() + 60000),
},
sound: 'beep.wav',
smallIcon: 'ic_stat_icon_config_sample',
iconColor: '#FF00FF',
},
],
});
};

// 检查权限
const checkPermissions = async () => {
const permissions = await LocalNotifications.checkPermissions();

console.log('permissions:', permissions);
};

// 请求权限
const requestPermissions = async () => {
const permissions = await LocalNotifications.requestPermissions();

console.log('permissions:', permissions);
};

// 检查是否启用了精确通知设置(仅限 Android 13+)
const checkExactNotificationSetting = async () => {
const result = await LocalNotifications.checkExactNotificationSetting();

console.log('Exact notification setting enabled:', result.enabled);
};

// 取消通知
const cancelNotifs = async () => {
await LocalNotifications.cancel({
notifications: [{ id: 1 }],
});
};

// 获取待处理的通知
const getPending = async () => {
const pending = await LocalNotifications.getPending();

console.log('pending notifications:', pending);
};

// 获取已发送的通知
const getDelivered = async () => {
const delivered = await LocalNotifications.getDelivered();

console.log('delivered notifications:', delivered);
};

// 注册用于接收操作的监听器
LocalNotifications.addListener('localNotificationReceived', (notification) => {
console.log('Notification received: ', notification);
});

LocalNotifications.addListener('localNotificationActionPerformed', (action) => {
console.log('Notification action performed', action);
});

允许的操作类型

这些是允许的通知操作类型:

描述Since
button按钮操作,文本来自操作 title6.0.0
textInput文本输入操作,文本来自操作 title,接受用户输入。用户提交文本后,inputValue 将在通知操作事件中返回。6.0.0

指定声音

要在通知中使用自定义声音,请遵循特定平台的说明。

iOS

对于 iOS,声音文件必须放在 res/sounds 文件夹中。

Android

对于 Android,声音文件必须放在 res/raw 文件夹中。

指定图标

在 Android 上,通知必须指定图标。如果没有指定图标,将使用应用图标,但会显示为白色或灰色(取决于 Android 版本)。

通知由一个状态栏图标(单色,对于 Oreo 及以上版本为透明)和通知抽屉中的图标组成。

状态栏图标(小图标)

状态栏图标应该仅包含白色像素和透明像素。配置 smallIcon 以指定此图标。它应该是没有扩展名的资源名称。

如果未指定,将使用 ic_stat_icon_config_sample

通知抽屉图标(大图标)

如果提供了 iconColorlargeIcon 中指定的图标(如果有)将着色为该颜色。

它应该是指向资源的文件 URI,例如:file:///path_to_icon.png

如果未指定,将使用应用启动器图标。

Android 通知渠道

从 Android 8.0(API 级别 26)开始,支持并推荐使用通知渠道。SDK 将按以下顺序获取传入推送通知的 channelId

  1. 首先检查传入通知是否设置了 channelId 从 FCM 控制台或通过其 API 发送推送通知时,可以指定 channelId
  2. 然后检查 AndroidManifest.xml 中可能给定的值。 如果你想创建并使用自己的默认渠道,请将 default_notification_channel_id 设置为你的通知渠道对象的 ID,如所示;FCM 将在传入消息未明确设置通知渠道时使用此值。
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
  1. 最后使用 Firebase SDK 为我们提供的后备 channelId FCM 提供了一个具有基本设置的默认通知渠道。此渠道将在收到第一条推送消息时由 Firebase SDK 创建。

API

checkPermissions()

checkPermissions() => Promise<PermissionStatus>

检查接收通知的权限。

Returns:

Promise<PermissionStatus>

Since: 5.0.0


requestPermissions()

requestPermissions() => Promise<PermissionStatus>

请求接收通知的权限。

Returns:

Promise<PermissionStatus>

Since: 5.0.0


schedule(...)

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

调度通知。

ParamType
options
ScheduleOptions

Returns:

Promise<ScheduleResult>

Since: 1.0.0


requestPermissionForAllChannels()

requestPermissionForAllChannels() => Promise<void>

请求用户启用系统设置中的所有通知渠道。

仅适用于 Android O 或更高版本(SDK 26+)。

Since: 6.0.0


cancel(...)

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

取消已调度的通知。

ParamType
options
CancelOptions

Since: 1.0.0


getPending()

getPending() => Promise<PendingResult>

获取待处理的通知列表。

Returns:

Promise<PendingResult>

Since: 1.0.0


getDeliveredNotifications()

getDeliveredNotifications() => Promise<DeliveredNotifications>

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

Returns:

Promise<DeliveredNotifications>

Since: 1.0.0


removeDeliveredNotifications(...)

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

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

ParamType
delivered
DeliveredNotifications

Since: 1.0.0


removeAllDeliveredNotifications()

removeAllDeliveredNotifications() => Promise<void>

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

Since: 1.0.0


removeAllPendingNotifications()

removeAllPendingNotifications() => Promise<void>

删除所有待处理的通知。

Since: 1.0.0


createChannel(...)

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

创建通知渠道。

仅适用于 Android O 或更高版本(SDK 26+)。

ParamType
channel
Channel

Since: 1.0.0


deleteChannel(...)

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

删除通知渠道。

仅适用于 Android O 或更高版本(SDK 26+)。

ParamType
args{ id: string; }

Since: 1.0.0


listChannels()

listChannels() => Promise<ListChannelsResult>

列出现有的通知渠道。

仅适用于 Android O 或更高版本(SDK 26+)。

Returns:

Promise<ListChannelsResult>

Since: 1.0.0


checkExactNotificationSetting()

checkExactNotificationSetting() => Promise<CheckExactNotificationSettingResult>

检查是否启用了精确通知设置。

仅适用于 Android 13 或更高版本(SDK 33+)。

Returns:

Promise<CheckExactNotificationSettingResult>

Since: 6.1.0


addListener('localNotificationReceived', ...)

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

当应用处于打开状态时,收到通知时调用。

ParamType
eventName'localNotificationReceived'
listenerFunc
(notification: LocalNotificationSchema) => void

Returns:

Promise<PluginListenerHandle>

Since: 1.0.0


addListener('localNotificationActionPerformed', ...)

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

对通知执行操作时调用。

ParamType
eventName'localNotificationActionPerformed'
listenerFunc
(actionPerformed: ActionPerformed) => void

Returns:

Promise<PluginListenerHandle>

Since: 1.0.0


removeAllListeners()

removeAllListeners() => Promise<void>

删除此插件的所有本地监听器。

Since: 1.0.0


Interfaces

AttachmentOptions

PropTypeDescriptionSince
idstring附件的唯一标识符。1.0.0
urlstring文件附件的 URL。可以是文件路径(file:///path/to/file)或资源 URI(content://...)。1.0.0
typestring附件的 MIME 类型。1.0.0
thumbnailHiddenboolean如果为 true,附件应隐藏在展开的通知中。仅适用于 iOS。6.1.0

ScheduleResult

PropTypeDescriptionSince
notificationsany[]包含已调度通知的数组,如果取消则返回空。1.0.0

CancelOptions

PropTypeDescriptionSince
notificationsany[]要取消的通知列表。1.0.0

PendingResult

PropTypeDescriptionSince
notifications
LocalNotificationSchema[]
待处理的通知列表。1.0.0

DeliveredNotifications

PropTypeDescriptionSince
notifications
LocalNotificationSchema[]
通知屏幕上可见的通知列表。1.0.0

Channel

PropTypeDescriptionDefaultSince
idstring渠道标识符。1.0.0
namestring此渠道的用户友好名称(呈现给用户)。1.0.0
descriptionstring此渠道的描述(呈现给用户)。1.0.0
soundstring应为发布到此渠道的通知播放的声音。重要性至少为 3 的通知渠道应该有声音。应指定声音文件的文件名,相对于 android app 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

PropTypeDescriptionSince
channelsChannel[]你的应用创建的所有渠道的列表。1.0.0

ScheduleOptions

PropTypeDescriptionSince
notifications
LocalNotificationSchema[]
要调度的通知列表。1.0.0

LocalNotificationSchema

PropTypeDescriptionSince
titlestring通知标题。1.0.0
bodystring通知正文。1.0.0
idnumber通知的唯一标识符。1.0.0
schedule
NotificationSchedule
通知的时间表信息。1.0.0
smallIconstring小图标资源仅支持 Android。如果未提供,将使用 ic_stat_icon_config_sample1.0.0
iconColorstring图标的十六进制颜色,格式为 #RRGGBB。仅适用于 Android。1.0.0
largeIconstring大图标。1.0.0
attachments
AttachmentOptions[]
附件。6.1.0
actionTypeIdstring操作类型的唯一标识符。1.0.0
extraany要传递的任何额外数据。1.0.0
soundstring通知的声音。1.0.0
autoCancelbooleanAndroid 特定:用户点击时是否自动取消通知。默认值为 true。1.0.0
ongoingbooleanAndroid 特定:是否为正在进行的。1.0.0
groupstringAndroid 特定:将通知分组在一起。1.0.0
groupSummarybooleanAndroid 特定:此通知是否为组的摘要。1.0.0
lightsbooleanAndroid 特定:通知是否应发出灯光。1.0.0
lightColorstringAndroid 特定:灯光的颜色,格式为 #AARRGGBB 或 #RRGGBB。1.0.0
vibrationbooleanAndroid 特定:通知是否应振动。1.0.0
lockscreenbooleanAndroid 特定:通知是否应显示在锁定屏幕上。1.0.0
launchUrlstringAndroid 特定:打开通知时应用应打开的 URL。6.0.0
launchbooleanAndroid 特定:是否在点击通知时启动应用。默认值为 false。1.0.0
prioritynumberAndroid 特定:优先级。应为 min、low、default、high 或 max 其中之一。1.0.0
threadsstringiOS 特定:用于将通知分组在一起的标识符。1.0.0
summaryArgumentstringiOS 特定:摘要参数。1.0.0
summaryArgumentCountnumberiOS 特定:摘要参数计数。1.0.0

NotificationSchedule

PropTypeDescriptionSince
atDate触发通知的日期。如果重复为空,则在设置此时间时触发通知。如果提供了重复,则忽略该日期的日期部分。1.0.0
repeatsboolean是否应重复通知。1.0.0
everystring通知应重复的频率。对于分钟和秒,如果用户超过一次,则使用带逗号分隔的单个值(例如:'minute', 'hour', 'day', 'week', 'month', 'year', '30,45')。1.0.0
countnumber通知应重复的次数。每次通知触发时计数器都会递减。直到计数达到零为止,通知都会被触发。1.0.0
onobject重复触发器的详细信息。包含 year(年份)类型为 numbermonth(月份,范围 0-11)类型为 numberday(日期)类型为 numberhour(小时)类型为 numberminute(分钟)类型为 number1.0.0
allowWhileIdlebooleanAndroid 特定:如果为 true,即使应用处于空闲状态,也会触发通知。1.0.0

ActionPerformed

PropTypeDescriptionSince
actionIdstring执行的操作的 ID。1.0.0
inputValuestring输入操作的值。5.0.0
notification
LocalNotificationSchema
在其上执行操作的通知。1.0.0

PluginListenerHandle

PropType
remove() => Promise<void>

CheckExactNotificationSettingResult

PropTypeDescriptionSince
enabledboolean是否启用了精确通知设置。6.1.0

PermissionState

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

PermissionStatus

PropTypeDescriptionSince
display
PermissionState
显示通知的权限状态。5.0.0
exact
PermissionState
精确闹钟的权限状态。6.1.0

Type Aliases

Importance

重要性级别。有关更多详细信息,请参阅 Android 开发者文档

1 | 2 | 3 | 4 | 5

Visibility

通知可见性。有关更多详细信息,请参阅 Android 开发者文档

-1 | 0 | 1