This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
Expo 通知
一个库,提供 API 来获取推送通知令牌并渲染、安排、接收和响应通知。
expo-notifications 提供了一个 API,用于获取推送通知令牌,以及显示、安排、接收和响应通知。
不要遗漏我们关于如何设置、发送和处理推送通知的指南。
警告 由
expo-notifications提供的推送通知(远程通知)功能在 Android 上的 Expo Go 中从 SDK 53 开始不可用。需要使用 开发构建 才能使用推送通知。本地通知(应用内通知)在 Expo Go 中仍然可用。
特性
🌐 Features
- 安排在特定日期或从现在起的某个时间发出一次性通知
- 安排通知在某个时间间隔内重复(或 iOS 上的日历日期匹配)
- 获取和设置应用徽章图标编号
- 获取原生设备推送令牌,以便你可以使用 FCM(适用于 Android)和 APNs(适用于 iOS)发送推送通知
- 获取一个 Expo 推送令牌,以便你可以使用 Expo Push Service 发送推送通知
- 在前台和后台收听传入的通知
- 聆听与通知的交互
- 当应用位于前台时处理通知
- 强制关闭通知中心/托盘中的通知
- 创建、更新和删除 Android 通知通道
- 在 Android 上设置通知的自定义图标和颜色
安装
🌐 Installation
If you are installing this in an existing React Native app, make sure to install expo in your project.
已知问题 Android
🌐 Known issues
在 Android 开发版本 中通过推送通知启动应用时,启动画面大约有 70% 的时间可能无法正确显示。图标和淡入淡出动画可能不会按预期出现。
🌐 When launching the app from a push notification in Android development builds, the splash screen may fail to display correctly about 70% of the time. The icon and fade animation may not appear as expected.
- 图标可能缺失
- 淡入淡出动画可能无法运行
- 只有背景颜色可能会短暂闪烁。
此问题仅影响调试版本,在发布版本中不会出现。为解决此问题,请在发布模式下(npx expo run:android --variant release)测试通知启动,以获得准确的行为。
🌐 This issue only affects debug builds and does not occur in release builds. To workaround it, test notification launches in release mode (npx expo run:android --variant release) for accurate behavior.
用法
🌐 Usage
查看下面的示例 Snack,了解通知的实际效果。推送通知可在物理设备、带有 Google Play 服务的 Android 模拟器以及 Xcode 14 或更高版本的 iOS 模拟器(macOS 13+、iOS 16+)上使用。
🌐 Check out the example Snack below to see Notifications in action. Push notifications work on physical devices, Android emulators with Google Play services, and iOS simulators on Xcode 14 or later (macOS 13+, iOS 16+).
向用户显示本地(应用内)通知
🌐 Present a local (in-app) notification to the user
import * as Notifications from 'expo-notifications'; Notifications.scheduleNotificationAsync({ content: { title: 'Look at that notification', body: "I'm so proud of myself!", }, trigger: null, });
通过导航处理推送通知
🌐 Handle push notifications with navigation
如果你想在收到推送通知时深层链接到应用中的特定屏幕,你可以配置 Expo 的任一导航系统来执行此操作。
🌐 If you'd like to deep link to a specific screen in your app when you receive a push notification, you can configure either of Expo's navigation systems to do that.
你可以使用 Expo Router 的内置深度链接来处理来自推送通知的传入 URL。只需配置根布局以监听传入和初始通知事件即可。
🌐 You can use Expo Router's built-in deep linking to handle incoming URLs from push notifications. Simply configure the root layout to listen for incoming and initial notification events.
React Navigation 的手动 链接配置 可以配置以处理来自推送通知的传入重定向:
🌐 React Navigation's manual linking configuration can be configured to handle incoming redirects from push notifications:
在React Navigation文档中查看更多详情。
🌐 See more details on React Navigation documentation.
配置
🌐 Configuration
证书
🌐 Credentials
请按照安装指南操作。
🌐 Follow the setup guide.
应用配置
🌐 App config
要配置 expo-notifications,请在应用配置(app.json 或 app.config.js)中使用内置的 config 插件 进行 EAS Build 设置,或使用 npx expo run:[android|ios]。该插件允许你配置以下属性,这些属性无法在运行时设置,需要构建新的应用二进制文件才能生效:
🌐 To configure expo-notifications, use the built-in config plugin in the app config (app.json or app.config.js) for EAS Build or with npx expo run:[android|ios]. The plugin allows you to configure the following properties that cannot be set at runtime and require building a new app binary to take effect:
Configurable properties
以下是在应用配置文件中使用配置插件的示例:
🌐 Here is an example of using the config plugin in the app config file:
当
enableRemoteNotifications设置为true(默认值)时,iOS 的 APNs 权限被设置为“开发”。Xcode 会在发布构建生成的归档中自动将其改为“生产”。 参考 这个关于 APNs 权限的 Stack Overflow 回答。当enableRemoteNotifications为false时,插件不会添加 APNs 权限。
Are you using this library in an existing React Native app?
学习如何在expo-notifications 仓库的安装说明中配置本地项目。
🌐 Learn how to configure the native projects in the installation instructions in the expo-notifications repository.
权限
🌐 Permissions
安卓
🌐 Android
- 在 Android 上,该模块需要权限来订阅设备启动事件。它用于在设备(重新)启动时设置定时通知。
RECEIVE_BOOT_COMPLETED权限会通过库的 AndroidManifest.xml 自动添加。 - 从 Android 12(API 级别 31)开始,要安排在准确时间触发的通知,你需要在 AndroidManifest.xml 中添加
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>。你可以阅读更多关于 准确闹钟权限 的信息。Android 14(API 级别 34)及更高版本默认会拒绝新安装应用的这个权限。可以使用getExactAlarmPermissionsAsync和requestExactAlarmPermissionsAsync来检查和请求它。delivery: 'alarmClock'触发选项也需要准确闹钟权限。在 Android 13(API 级别 33)及更高版本中,闹钟、计时器和日历应用可以改为声明<uses-permission android:name="android.permission.USE_EXACT_ALARM"/>。系统会授予该权限且无需用户提示。Google Play 的准确闹钟政策 将USE_EXACT_ALARM限制在特定类型的应用中。 - 在 Android 13 上,应用用户必须通过操作系统自动触发的权限提示来选择是否接收通知。该提示在至少创建一个通知渠道之前不会出现。必须在调用
getDevicePushTokenAsync或getExpoPushTokenAsync之前调用setNotificationChannelAsync来获取推送令牌。你可以在官方文档中了解有关 Android 13 新通知权限行为的更多信息。
iOS
无需使用说明,请参见 通知相关权限。
🌐 No usage description is required, see notification-related permissions.
解释 iOS 权限响应
🌐 Interpret the iOS permissions response
在 iOS 上,发送通知的权限比在 Android 上更为细化。这就是为什么你应该依赖 NotificationPermissionsStatus 的 ios.status 字段,而不是根 status 字段。
🌐 On iOS, permissions for sending notifications are a little more granular than they are on Android. This is why you should rely on the NotificationPermissionsStatus's ios.status field, instead of the root status field.
该值将是以下之一,可在 Notifications.IosAuthorizationStatus 下访问:
🌐 This value will be one of the following, accessible under Notifications.IosAuthorizationStatus:
NOT_DETERMINED:用户尚未选择是否允许应用安排通知DENIED:该应用无权安排或接收通知AUTHORIZED:该应用被授权安排或接收通知PROVISIONAL:该应用被临时授权发布非中断性用户通知EPHEMERAL:该应用被授权在有限的时间内安排或接收通知
通知事件监听器
🌐 Notification events listeners
通知事件包括传入通知、用户对通知执行的操作(这可以是点击通知,或通过通知类别与通知交互)、以及通知可能被丢弃的少数情况。
🌐 Notification events include incoming notifications, interactions your users perform with notifications (this can be tapping on a notification, or interacting with it via notification categories), and rare occasions when your notifications may be dropped.
推送通知行为部分中列出了几个已被暴露和记录的监听器。
🌐 Several listeners are exposed and documented in the Push notification behaviors section.
无头(后台)通知
🌐 Headless (Background) notifications
请参阅《你需要知道的事项》(/push-notifications/what-you-need-to-know) 指南中关于无头后台通知的 定义。
🌐 See the definition of Headless Background Notifications in the What you need to know guide.
要在应用处于后台或未运行时处理通知,你需要执行以下操作:
🌐 To handle notifications while the app is in the background or not running, you need to do the following:
然后发送推送通知:
🌐 Then send a push notification which:
- 仅包含
data键(没有title、body) - iOS 已设置
contentAvailable: true— 查看 Expo 推送通知服务有效载荷格式
后台通知配置 iOS
🌐 Background notification configuration
要在 iOS 上使用无界面(后台)推送通知,你的应用 Info.plist 文件中的 UIBackgroundModes 数组中需要包含 remote-notification 值。
🌐 To be able to use headless (background) notifications push notifications on iOS, the remote-notification value needs to be present in the UIBackgroundModes array in your app's Info.plist file.
如果你正在使用 CNG,请将配置插件的 enableBackgroundRemoteNotifications 属性 设置为 true,预构建将自动应用正确的配置。
附加信息
🌐 Additional information
设置自定义通知声音
🌐 Set custom notification sounds
要向你的应用添加自定义推送通知声音,请在你的 app.json 文件中添加 expo-notifications 插件,然后在 sounds 键下提供一个本地路径数组,这些路径指向可用作自定义通知声音的音频文件。这些本地路径是相对于你的项目的本地路径。
🌐 To add custom push notification sounds to your app, add the expo-notifications plugin to your app.json file and then under the sounds key, provide an array of local paths to sound files that can be used as custom notification sounds. These local paths are local to your project.
在构建应用后,这些文件数组可以在 NotificationContentInput 和 NotificationChannelInput 中使用。你只需要提供基本的文件名。下面是使用上述配置的示例:
🌐 After building your app, the array of files will be available for use in both NotificationContentInput and NotificationChannelInput.
You only need to provide the base filename. Here's an example using the config above:
await Notifications.setNotificationChannelAsync('new_emails', { name: 'E-mail notifications', importance: Notifications.AndroidImportance.HIGH, sound: 'mySoundFile.wav', // Provide ONLY the base filename }); await Notifications.scheduleNotificationAsync({ content: { title: "You've got mail! 📬", sound: 'mySoundFile.wav', // Provide ONLY the base filename }, trigger: { type: Notifications.SchedulableTriggerInputTypes.TIME_INTERVAL, seconds: 2, channelId: 'new_emails', }, });
如果你愿意,你也可以手动将通知文件添加到你的 Android 和 iOS 项目中:
🌐 You can also manually add notification files to your Android and iOS projects if you prefer:
在安卓上手动添加通知音
在 Android 8.0 及以上版本中,为通知播放自定义声音不仅仅是设置 NotificationContentInput 上的 sound 属性。你还需要使用适当的 sound 配置 NotificationChannel,并在发送/安排通知时使用它。
🌐 On Androids 8.0+, playing a custom sound for a notification requires more than setting the sound property on the NotificationContentInput.
You will also need to configure the NotificationChannel with the appropriate sound, and use it when sending/scheduling the notification.
要使下面的示例工作,你需要将你的 email_sound.wav 文件放置在 android/app/src/main/res/raw/ 中。
🌐 For the example below to work, you would place your email_sound.wav file in android/app/src/main/res/raw/.
// Prepare the notification channel await Notifications.setNotificationChannelAsync('new_emails', { name: 'E-mail notifications', importance: Notifications.AndroidImportance.HIGH, sound: 'email_sound.wav', // <- for Android 8.0+, see channelId property below }); // Eg. schedule the notification await Notifications.scheduleNotificationAsync({ content: { title: "You've got mail! 📬", body: 'Open the notification to read them all', sound: 'email_sound.wav', // <- for Android below 8.0 }, trigger: { type: Notifications.SchedulableTriggerInputTypes.TIME_INTERVAL, seconds: 2, channelId: 'new_emails', // <- for Android 8.0+, see definition above }, });
在 iOS 上手动添加通知声音
在 iOS 上,只需将你的音频文件放入 Xcode 项目中(见下图),然后在你的 NotificationContentInput 中指定该音频文件,像这样:
🌐 On iOS, all that's needed is to place your sound file in your Xcode project (see the screenshot below),
and then specify the sound file in your NotificationContentInput, like this:
await Notifications.scheduleNotificationAsync({ content: { title: "You've got mail! 📬", body: 'Open the notification to read them all', sound: 'notification.wav', }, trigger: { // ... }, });
推送通知负载规范
🌐 Push notification payload specification
请参阅 消息请求格式。
🌐 See Message request format.
管理互动通知的通知类别
🌐 Manage notification categories for interactive notifications
通知类别允许你创建互动推送通知,使用户可以通过按钮或文本回复直接对收到的通知作出响应。类别定义了用户可以采取的操作集,然后通过在 NotificationContent 中指定 categoryIdentifier 将这些操作应用于通知。
🌐 Notification categories allow you to create interactive push notifications, so that a user can respond directly to the incoming notification
either via buttons or a text response. A category defines the set of actions a user can take, and then those actions are applied to a notification
by specifying the categoryIdentifier in the NotificationContent.
在 iOS 上,通知类别还允许你进一步自定义通知。对于每个类别,你可以设置用户可以执行的互动操作,并配置一些内容,比如当用户关闭你应用的通知预览时显示的占位符文本。
🌐 On iOS, notification categories also allow you to customize your notifications further. With each category, you can set the interactive actions a user can take and configure things like the placeholder text to display when the user disables notification previews for your app.
特定平台指南
🌐 Platform-specific guides
处理通知渠道 Android 8+
🌐 Handling notification channels
从 Android 8.0(API 级别 26)开始,所有通知都必须分配到一个渠道。对于每个渠道,你可以设置应用于该渠道中所有通知的视觉和声音行为。然后,用户可以更改这些设置,并决定你的应用的哪些通知渠道应具有干扰性或是否可见,正如 Android 开发者文档 所述。
🌐 Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel. For each channel, you can set the visual and auditory behavior that is applied to all notifications in that channel. Then, users can change these settings and decide which notification channels from your app should be intrusive or visible at all, as Android developer docs states.
如果你未指定通知通道,expo-notifications 将为你创建一个备用通道,名为 杂项。
我们鼓励你始终确保为应用设置具有信息性名称的适当通道,并始终向这些通道发送通知。
🌐 If you do not specify a notification channel, expo-notifications will create a fallback channel for you, named Miscellaneous.
We encourage you to always ensure appropriate channels with informative names are set up for the application and to always send notifications to these channels.
对于不支持此功能的平台(Android 8.0(26)以下版本和 iOS),调用这些方法不会有任何效果。
自定义通知图标和颜色 Android
🌐 Custom notification icon and colors
你可以使用 expo-notifications 配置插件 和 Expo Prebuild 在项目中为通知配置 icon 和 color 键。这些是构建时设置,因此你需要使用 eas build -p android 或 npx expo run:android 重新编译本地 Android 应用才能看到更改。
🌐 You can configure the icon and color keys for notification in the project by using the expo-notifications config plugin with Expo Prebuild. These are build-time settings, so you'll need to recompile your native Android app with eas build -p android or npx expo run:android to see the changes.
对于你的通知图标,请确保遵循谷歌的设计指南(图标必须全白且背景透明),否则可能无法按预期显示。
🌐 For your notification icon, make sure you follow Google's design guidelines (the icon must be all white with a transparent background) or else it may not be displayed as intended.
你也可以在你的 NotificationContentInput 中直接在 color 属性下为每条通知设置自定义通知颜色。
🌐 You can also set a custom notification color per-notification directly in your NotificationContentInput under the color attribute.
应用接口
🌐 API
import * as Notifications from 'expo-notifications';
No API data file found, sorry!