@capacitor/push-notifications
Push Notifications API 提供对原生推送通知的访问。
安装
npm install @capacitor/push-notifications
npx cap sync
iOS 平台
在 iOS 上,您必须启用 Push Notifications 功能。请参阅 设置功能 了解如何启用该功能。
启用 Push Notifications 功能后,将以下内容添加到您的应用的 AppDelegate.swift:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
}
Android 平台
Push Notification API 使用 Firebase Cloud Messaging SDK 处理通知。请参阅 在 Android 上设置 Firebase Cloud Messaging 客户端应用 并按照说明创建 Firebase 项目和注册您的应用程序。
无需将 Firebase SDK 添加到您的应用或编辑应用清单——Push Notifications 已为您提供了这些。唯一需要的是将 Firebase 项目的 google-services.json 文件添加到应用的模块(应用级)目录中。
Android 13 需要权限检查才能接收推送通知。当目标 SDK 为 33 时,您需要相应调用 checkPermissions() 和 requestPermissions()。
从 Android 15 开始,用户可以在私人空间中安装应用。用户可以随时锁定其私人空间,这意味着在用户解锁之前不会显示推送通知。
无法检测应用是否安装在私人空间中。因此,如果您的应用显示任何关键通知,请告知您的用户避免在私人空间中安装该应用。
有关应用与私人空间相关行为变化的更多信息,请参阅 Android 文档。
变量
此插件将使用以下项目变量(在应用的 variables.gradle 文件中定义):
firebaseMessagingVersioncom.google.firebase:firebase-messaging的版本(默认值:25.0.1)
推送通知图标
在 Android 上,应将具有适当名称的推送通知图标添加到 AndroidManifest.xml 文件中:
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/push_icon_name" />
如果未指定图标,Android 将使用 应用图标,但推送图标应为透明背景上的白色像素。由于应用图标通常不是这样的,它会显示一个白色方块或圆圈。因此建议为推送通知提供单独的图标。
Android Studio 有一个图标生成器,您可以使用它来创建推送通知图标。
推送通知频道
从 Android 8.0(API 级别 26)及更高版本开始,支持并推荐使用通知频道。SDK 将按以下顺序为传入的推送通知派生 channelId:
- 首先检查传入的通知是否设置了
channelId。 从 FCM 仪表板或通过其 API 发送推送通知时,可以指定channelId。 - 然后检查
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" />
- 最后使用 Firebase SDK 为我们提供的备用
channelId。 FCM 开箱即用地提供了一个具有基本设置的默认通知频道。此频道将在收到第一条推送消息时由 Firebase SDK 创建。
警告 使用选项 1 或 2 时,您仍需要在代码中创建一个与所选选项使用的 ID 匹配的通知频道。您可以使用
createChannel(...)来实现。如果不这样做,SDK 将回退到选项 3。
前台时的推送通知外观
您可以配置应用在前台时推送通知的显示方式。
| 属性 | 类型 | 描述 | 自版本 |
|---|---|---|---|
presentationOptions | PresentationOption[] | 这是您可以组合的字符串数组。数组中可能的值有:- badge:更新应用图标上的徽章计数(默认值)- sound:收到推送通知时设备将响铃/振动 - alert:在 iOS 上已弃用。 请使用 banner 和 list。在 Android 上,此值仍用于显示通知。- banner:推送通知显示为横幅。在 Android 上,默认为与 alert 相同的行为。- list:推送通知显示在通知中心。在 Android 上,默认为与 alert 相同的行为。如果不需要任何选项,可以提供空数组。badge 仅适用于 iOS。 | 1.0.0 |
示例
在 capacitor.config.json 中:
{
"plugins": {
"PushNotifications": {
"presentationOptions": ["badge", "sound", "alert", "banner", "list"]
}
}
}
在 capacitor.config.ts 中:
/// <reference types="@capacitor/push-notifications" />
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
plugins: {
PushNotifications: {
presentationOptions: ["badge", "sound", "alert", "banner", "list"],
},
},
};
export default config;
静默推送通知 / 仅数据通知
iOS
此插件不支持 iOS 静默推送(远程通知)。我们建议使用原生代码解决方案处理这些类型的通知,请参阅 向您的应用推送后台更新。
Android
此插件支持仅数据通知,但如果应用已被杀死,将不会调用 pushNotificationReceived。要处理此场景,您需要创建一个扩展 FirebaseMessagingService 的服务,请参阅 处理 FCM 消息。
常见问题
在 Android 上,各种系统 和应用状态可能会影响推送通知的投递:
- 如果设备已进入 Doze 模式,您的应用可能具有受限的能力。为了增加收到通知的机会,请考虑使用 FCM 高优先级消息。
- 开发和生产之间的行为存在差异。尝试在 Android Studio 启动之外测试您的应用。在此处阅读更多信息。
示例
import { PushNotifications } from '@capacitor/push-notifications';
const addListeners = async () => {
await PushNotifications.addListener('registration', token => {
console.info('Registration token: ', token.value);
});
await PushNotifications.addListener('registrationError', err => {
console.error('Registration error: ', err.error);
});
await PushNotifications.addListener('pushNotificationReceived', notification => {
console.log('Push notification received: ', notification);
});
await PushNotifications.addListener('pushNotificationActionPerformed', notification => {
console.log('Push notification action performed', notification.actionId, notification.inputValue);
});
}
const registerNotifications = async () => {
let permStatus = await PushNotifications.checkPermissions();
if (permStatus.receive === 'prompt') {
permStatus = await PushNotifications.requestPermissions();
}
if (permStatus.receive !== 'granted') {
throw new Error('User denied permissions!');
}
await PushNotifications.register();
}
const getDeliveredNotifications = async () => {
const notificationList = await PushNotifications.getDeliveredNotifications();
console.log('delivered notifications', notificationList);
}
API 参考
register()unregister()getDeliveredNotifications()removeDeliveredNotifications(...)removeAllDeliveredNotifications()createChannel(...)deleteChannel(...)listChannels()checkPermissions()requestPermissions()addListener('registration', ...)addListener('registrationError', ...)addListener('pushNotificationReceived', ...)addListener('pushNotificationActionPerformed', ...)removeAllListeners()- Interfaces
- Type Aliases
register()
register() => Promise<void>
注册应用以接收推送通知。
此方法将触发 'registration' 事件(带有推送令牌)或
'registrationError'(如果出现问题)。它不会提示用户授予通知权限,
请先使用 requestPermissions()。
自版本: 1.0.0
unregister()
unregister() => Promise<void>
取消注册应用的推送通知。
这将在 Android 上删除 Firebase 令牌,并在 iOS 上取消注册 APNS。
自版本: 5.0.0
getDeliveredNotifications()
getDeliveredNotifications() => Promise<DeliveredNotifications>
获取通知屏幕上可见的通知列表。