简体   繁体   中英

Cancel/dismiss notification on icon

I'm using OneSignal to display notifications to my user. The notifications work fine but, I noticed that if I cancel the notification "swiping" it in the notification bar then the notification remains for ever, here is a image showing the notification on the app icon that I would like to dismiss as soon as the application is opened:

图标

I have seen this question, showing that I can dismiss the notification by doing:

NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (nMgr!=null) {
    nMgr.cancelAll();
}

But this cancels the notification in that notification bar, but the notification on the app icon remain, any idea how I can cancel it as soon as my application is opened?

EDIT 1:

I added the above in OnCreate , also in OnResume as mentioned in the answer below, but the 1 still gets displayed on the app icon.

I found that with OneSignal I can disable badges by adding the following in my manifest:

<application ...>

    <meta-data android:name="com.onesignal.BadgeCount" android:value="DISABLE" />

</application>

Starting with 8.0 (API level 26), notification badges can be disabled by calling the following :

String id = "my_channel_01";
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
mChannel.setDescription(description);
mChannel.setShowBadge(false);

NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(mChannel);

With this library I can also set badge numbers manually after disabling them. Note, this only supports certain manufactured devices (Samsung, LG, Sony and HTC).

the above code is perfect but the thing you need to do is you need to add this code inside the onResume() Like

@Override
protected void onResume() {
    super.onResume();

    NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    nm.cancelAll();
}

thats do the trick for you . :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM