I use OneSignal push notifications. When android app is in foreground and receives a notification, it creates an alert box with the notification. How to prevent this from appearing when receiving notifications?
How to prevent alert with incoming OneSignal notification?
12.6k views Asked by user3671635 At
6
There are 6 answers
0
On
Here is how to handle notifications while the app is in the foreground in the newest version 11, from https://documentation.onesignal.com/docs/mobile-sdk#handling-notifications-before-theyre-presented-when-the-app-is-in-the-foreground :
let myLifecyleListener = function(event) {
/// Display Notification, preventDefault to not display
event.preventDefault();
// Handle app in focus notifications here:
console.log('foreground notification received:', event.notification)
// Use notification.display() to display the notification after some async work
// Uncomment this line if you would like the notification to be displayed
// event.notification.display();
}
Then apply the handler: (This code applies to the Cordova version)
window.plugins.OneSignal.Notifications.addEventListener("foregroundWillDisplay", myLifecyleListener);
0
On
It's changed in OneSignal 4.0.
For Kotlin:
OneSignal.setNotificationWillShowInForegroundHandler { notificationReceivedEvent ->
notificationReceivedEvent.complete(null)
}
For Java:
OneSignal.setNotificationWillShowInForegroundHandler(new NotificationWillShowInForegroundHandler() {
@Override
void notificationWillShowInForeground(OSNotificationReceivedEvent notificationReceivedEvent) {
notificationReceivedEvent.complete(null);
}
});
0
On
I had similar issues and I resolved it by using inFocusDisplaying
here's how to use this in android.
public class MyApplicationClass extends Application {
private static Context context;
PlayerIdsession session;
public static Context getContext() {
return context;
}
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
//MyNotificationOpenedHandler : This will be called when a notification is tapped on.
//MyNotificationReceivedHandler : This will be called when a notification is received while your app is running.
OneSignal.startInit(this)
.setNotificationOpenedHandler(new MyNotiOpenedHandler())
.setNotificationReceivedHandler( new MyNotiReceivedHandler() )
.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
.init();
OneSignal.idsAvailable(new OneSignal.IdsAvailableHandler() {
@Override
public void idsAvailable(String userId, String registrationId) {
if (userId != null){
session=new PlayerIdsession(context);
session.savePlayerId(userId);
Log.d("debug", "PlayerId:" + userId);
}
/* if (registrationId != null){
Log.d("debug", "registrationId:" + registrationId);
}*/
}
});
}
}
From The SDK documentation - When you startInit OneSignal, make sure to call inFocusDisplaying with "None" to disable OneSignal's in app AlertBox.
also on NotificationReceivedHandler section -