This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

处理传入通知

了解如何响应应用收到的通知并根据事件采取行动。


expo-notifications 库包含事件监听器,用于处理你的应用在接收到通知时的响应方式。

🌐 The expo-notifications library contains event listeners that handle how your app responds when receiving a notification.

通知事件监听器

🌐 Notification event listeners

当收到或与通知进行交互时,addNotificationReceivedListener 和 addNotificationResponseReceivedListener 事件监听器会接收到一个对象。

🌐 The addNotificationReceivedListener and addNotificationResponseReceivedListener event listeners receive an object when a notification is received or interacted with.

这些监听器允许你在应用打开和前台时以及应用后台或关闭且用户点击通知时收到通知时添加行为。

🌐 These listeners allow you to add behavior when notifications are received while your app is open and foregrounded and when your app is backgrounded or closed and the user taps on the notification.

useEffect(() => { registerForPushNotificationsAsync().then(token => setExpoPushToken(token)); const notificationListener = Notifications.addNotificationReceivedListener(notification => { console.log(notification); }); const responseListener = Notifications.addNotificationResponseReceivedListener(response => { console.log(response); }); return () => { notificationListener.remove(); responseListener.remove(); }; }, []);
Android 通知对象示例,来自 addNotificationReceivedListener

使用 Notifications.addNotificationReceivedListener 时,回调函数接收到的 notification 对象示例:

🌐 Sample of the notification object received by the callback function when using Notifications.addNotificationReceivedListener:

// console.log(notification); { "request": { "trigger": { "remoteMessage": { "originalPriority": 2, "sentTime": 1724782348210, "notification": { "usesDefaultVibrateSettings": false, "color": null, "channelId": null, "visibility": null, "sound": null, "tag": null, "bodyLocalizationArgs": null, "imageUrl": null, "title": "Chat App", "ticker": null, "eventTime": null, "body": "New message from John Doe", "titleLocalizationKey": null, "notificationPriority": null, "icon": null, "usesDefaultLightSettings": false, "sticky": false, "link": null, "titleLocalizationArgs": null, "bodyLocalizationKey": null, "usesDefaultSound": false, "clickAction": null, "localOnly": false, "lightSettings": null, "notificationCount": null }, "data": { "channelId": "default", "message": "New message from John Doe", "title": "Chat App", "body": "{\"senderId\":\"user123\",\"senderName\":\"John Doe\",\"messageId\":\"msg789\",\"conversationId\":\"conversation-456\",\"messageType\":\"text\",\"timestamp\":1724766427}", "scopeKey": "@betoatexpo/expo-notifications-app", "experienceId": "@betoatexpo/expo-notifications-app", "projectId": "51092087-87a4-4b12-8008-145625477434" }, "to": null, "ttl": 0, "collapseKey": "dev.expo.notificationsapp", "messageType": null, "priority": 2, "from": "115310547649", "messageId": "0:1724782348220771%0f02879c0f02879c" }, "channelId": "default", "type": "push" }, "content": { "autoDismiss": true, "title": "Chat App", "badge": null, "sticky": false, "sound": "default", "body": "New message from John Doe", "subtitle": null, "data": { "senderId": "user123", "senderName": "John Doe", "messageId": "msg789", "conversationId": "conversation-456", "messageType": "text", "timestamp": 1724766427 } }, "identifier": "0:1724782348220771%0f02879c0f02879c" }, "date": 1724782348210 }

你可以通过记录 notification.request.content.data 对象直接访问通知的自定义数据:

🌐 You can directly access the notification custom data by logging the notification.request.content.data object:

// console.log(notification.request.content.data); { "senderId": "user123", "senderName": "John Doe", "messageId": "msg789", "conversationId": "conversation-456", "messageType": "text", "timestamp": 1724766427 }
iOS 通知对象示例,来自 addNotificationReceivedListener

使用 Notifications.addNotificationReceivedListener 时,回调函数接收到的 notification 对象示例:

🌐 Sample of the notification object received by the callback function when using Notifications.addNotificationReceivedListener:

// console.log(notification); { "request": { "trigger": { "class": "UNPushNotificationTrigger", "type": "push", "payload": { "experienceId": "@betoatexpo/expo-notifications-app", "projectId": "51092087-87a4-4b12-8008-145625477434", "scopeKey": "@betoatexpo/expo-notifications-app", "aps": { "thread-id": "", "category": "", "badge": 1, "alert": { "subtitle": "Hey there! How's your day going?", "title": "Chat App", "launch-image": "", "body": "New message from John Doe" }, "sound": "default" }, "body": { "messageId": "msg789", "timestamp": 1724766427, "messageType": "text", "senderId": "user123", "senderName": "John Doe", "conversationId": "conversation-456" } } }, "identifier": "3AEB849E-9059-4D09-BC3B-9A0B104CF062", "content": { "body": "New message from John Doe", "sound": "default", "launchImageName": "", "badge": 1, "subtitle": "Hey there! How's your day going?", "title": "Chat App", "data": { "conversationId": "conversation-456", "senderName": "John Doe", "senderId": "user123", "messageType": "text", "timestamp": 1724766427, "messageId": "msg789" }, "summaryArgument": null, "categoryIdentifier": "", "attachments": [], "interruptionLevel": "active", "threadIdentifier": "", "targetContentIdentifier": null, "summaryArgumentCount": 0 } }, "date": 1724798493.0589335 }

你可以通过记录 notification.request.content.data 对象直接访问通知的自定义数据:

🌐 You can directly access the notification custom data by logging the notification.request.content.data object:

// console.log(notification.request.content.data); { "senderId": "user123", "senderName": "John Doe", "messageId": "msg789", "conversationId": "conversation-456", "messageType": "text", "timestamp": 1724766427 }

有关这些对象的更多信息,请参阅 Notification 文档。

🌐 For more information on these objects, see Notification documentation.

前台通知行为

🌐 Foreground notification behavior

在 SDK 57 及更早版本中,默认情况下前台通知根本不会显示。要显示它,你必须设置一个处理器来通过 Notifications.setNotificationHandler 请求它。如果处理器在 3 秒内没有响应,通知就会被丢弃。

🌐 In SDK 57 and earlier, a foreground notification is not shown at all by default. To show it, you have to set a handler that asks for it using Notifications.setNotificationHandler. A handler that does not respond within 3 seconds drops the notification.

在 SDK 58 及更高版本中,当你的应用处于前台时收到通知会默认显示。它会播放声音、显示横幅、出现在通知列表中,并设置应用角标。如果通知的处理程序在 3 秒内没有响应,它也会以相同的方式显示。

🌐 In SDK 58 and later, a notification that arrives while your app is foregrounded is shown by default. It plays a sound, shows a banner, appears in the notification list, and sets the app badge. A notification whose handler does not respond within 3 seconds is shown the same way.

要改变行为,请使用 Notifications.setNotificationHandler 和 handleNotification() 回调来设置以下选项:

🌐 To change the behavior, use Notifications.setNotificationHandler with the handleNotification() callback to set the following options:

  • shouldPlaySound
  • shouldSetBadge
  • shouldShowBanner
  • shouldShowList
Notifications.setNotificationHandler({ handleNotification: async () => ({ shouldPlaySound: false, shouldSetBadge: false, shouldShowBanner: true, shouldShowList: true, }), });

禁用通知处理程序

🌐 Disable the notification handler

在 SDK 58 及更高版本中,如果想阻止 expo-notifications 决定是否显示传入通知,请传入 null:

🌐 In SDK 58 and later, to stop expo-notifications from deciding whether an incoming notification shows, pass null:

Notifications.setNotificationHandler(null);

在安卓上,当你的应用处于前台时,通知就不会显示。在 iOS 上,这个决定交给另一个库设置的 UNUserNotificationCenterDelegate。如果没有库设置,通知就不会显示。

🌐 On Android, the notification is then not shown while your app is in the foreground. On iOS, the decision goes to the UNUserNotificationCenterDelegate that another library sets. If no library sets one, the notification is not shown.

关闭通知行为

🌐 Closed notification behavior

在安卓系统上,用户可以设置某些操作系统级别的设置,通常涉及性能和电池优化,这可能会导致应用关闭时通知无法送达。例如,在使用安卓9及以下版本的OnePlus设备上,其中一个这样的设置是深度清理选项。

🌐 On Android, users can set certain OS-level settings, usually revolving around performance and battery optimization, that can prevent notifications from being delivered when the app is closed. For example, one such setting is the Deep Clear option on OnePlus devices using Android 9 and lower versions.