首页指南参考教程

接收通知

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


expo-notifications 库包含事件监听器,用于处理应用在收到通知时如何响应。

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

通知事件监听器

¥Notification event listeners

当接收到通知或与之交互时,addNotificationReceivedListeneraddNotificationResponseReceivedListener 事件监听器会接收一个对象。

¥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));

  notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
    setNotification(notification);
  });

  responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
    console.log(response);
  });

  return () => {
    Notifications.removeNotificationSubscription(notificationListener.current);
    Notifications.removeNotificationSubscription(responseListener.current);
  };
}, []);

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

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

前台通知行为

¥Foreground notification behavior

要处理应用处于前台时收到通知时的行为,请使用 Notifications.setNotificationHandlerhandleNotification() 回调来设置以下选项:

¥To handle the behavior when notifications are received when your app is foregrounded, use Notifications.setNotificationHandler with the handleNotification() callback to set the following options:

  • shouldShowAlert

  • shouldPlaySound

  • shouldSetBadge

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

关闭通知行为

¥Closed notification behavior

在 Android 上,用户可以设置某些操作系统级别的设置,通常围绕性能和电池优化,这可以防止在应用关闭时发送通知。例如,使用 Android 9 及更低版本的 OnePlus 设备上的 Deep Clear 选项就是此类设置之一。

¥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.

Expo 中文网 - 粤ICP备13048890号