Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expo: don't show notification if app is open in foreground

I am developing a react-native messaging app with Expo. Every time a user receives a new message, I send a notification from my server.

Is there any way to not display the notification if the app is currently open?

Right now I am using this as soon as the notification is received:

Notifications.dismissNotificationAsync(notification.notificationId);

But there is a 0.5 second delay where the notification has time to appear in the tray and trigger a sound before it gets dismissed. I would like to not show it at all.

like image 493
Ryan Pergent Avatar asked Jun 20 '19 15:06

Ryan Pergent


2 Answers

When a notification is received while the app is running, using setNotificationHandler you can set a callback that will decide whether the notification should be shown to the user or not.

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

When a notification is received, handleNotification is called with the incoming notification as an argument. The function should respond with a behavior object within 3 seconds, otherwise the notification will be discarded. If the notification is handled successfully, handleSuccess is called with the identifier of the notification, otherwise (or on timeout) handleError will be called.

The default behavior when the handler is not set or does not respond in time is not to show the notification.

If you don't use setNotificaitonHandler, the new notifications will not be displayed while the app is in foreground.

So you can simply set setNotificationHandler to null when your app is initialized.


Notifications.setNotificationHandler(null);

See Documentaition

like image 142
Amjed Ali Avatar answered Sep 19 '22 02:09

Amjed Ali


The answer is yes to your question

Is there any way to not display the notification if the app is currently open?

The default behavior of Notification in Expo is not to show notification if the App is in foreground. You must have implemented Notifications.setNotificationHandler similar to the following code -

// *** DON'T USE THE FOLLOWING CODE IF YOU DON'T WANT NOTIFICATION TO BE DISPLAYED
// WHILE THE APP IS IN FOREGROUND! ***
// --------------------------------------------------
// Sets the handler function responsible for deciding
// what to do with a notification that is received when the app is in foreground
/*
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});
*/

If you don't use setNotificaitonHandler, the new notifications will not be displayed while the app is in foreground.

like image 44
hafij Avatar answered Sep 21 '22 02:09

hafij