Learn how to respond to a notification received by your app and take action based on the event.
The expo-notifications
library contains event listeners that handle how your app responds when receiving a notification.
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);
};
}, []);
For more information on these objects, see Notification
documentation.
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,
}),
});
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.
A collection of common questions about Expo's push notification service.