'Discard a push notification when received on device

I'm using OneSignal to send push notifications to iOS and Android devices. Is it possible to discard a push notification when it's received on a iOS and Android device? It's not all of them, but some based on the payload data and if the user has the device in the background or foreground.

Update:

"discard" meaning that it is never shown as a notification.

What are my options when I don't want to disturb users with updates if they are already in foreground using their app, but in background I like to show the notification?



Solution 1:[1]

In OneSignal you want to use setNotificationWillShowInForegroundHandler method to decide whether the need to show a notification to the user or not.

For Android

OneSignal.setNotificationWillShowInForegroundHandler(new NotificationWillShowInForegroundHandler() {
   @Override
   void notificationWillShowInForeground(OSNotificationReceivedEvent notificationReceivedEvent) {
     OSNotification notification = notificationReceivedEvent.getNotification();
     // Get custom additional data you sent with the notification
     JSONObject data = notification.getAdditionalData();

     if (/* some condition */ ) {
        // Complete with a notification means it will show
        notificationReceivedEvent.complete(notification);
     }
     else {
       // Complete with null means don't show a notification
       notificationReceivedEvent.complete(null);
    }
  }
});

For IOS

let notificationWillShowInForegroundBlock: OSNotificationWillShowInForegroundBlock = { notification, completion in
  print("Received Notification: ", notification.notificationId ?? "no id")
  print("launchURL: ", notification.launchURL ?? "no launch url")
  print("content_available = \(notification.contentAvailable)")

  if notification.notificationId == "example_silent_notif" {
    // Complete with null means don't show a notification  
    completion(nil)
  } else {
    // Complete with a notification means it will show
    completion(notification)
  }
}
OneSignal.setNotificationWillShowInForegroundHandler(notificationWillShowInForegroundBlock)

Note: For more info, you can check the documentation.

https://documentation.onesignal.com/docs/sdk-notification-event-handlers#foreground-notification-received-event

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Suraj Bahadur