111

Is it possible to clear a notification programatically?

I tried it with the NotificationManager but its not working. Is there any other way I can do it?

Irfan DANISH
  • 8,349
  • 12
  • 42
  • 67
rahul
  • 1,139
  • 2
  • 8
  • 4

17 Answers17

246

Use the following code to cancel a Notification:

NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);

In this code there is alway the same id used for notifications. If you have different notifications that need to be canceled you have to save the ids that you used to create the Notification.

Janusz
  • 187,060
  • 113
  • 301
  • 369
  • 10
    I don't know why this isn't upvoted more and selected as the answer. This was the solution I was looking for. Thanks! – loeschg Jan 29 '13 at 23:48
  • 3
    What should be the notification id here? – Deepak Nov 23 '15 at 07:50
  • This indeed works. But once I cancel a notification, all subsequent notifications do not show the notification message text (which I set using `setContentText`) though I set the priority to 2. Any suggestions? – Iqbal Feb 26 '16 at 12:10
  • Not working if notification flag set as Notification.FLAG_NO_CLEAR – Anand Savjani Dec 02 '16 at 04:28
  • 2
    for all and if you dont know which id, if (notificationManager != null) { notificationManager.cancelAll(); } – mehmet Dec 25 '17 at 09:31
  • @Deepak To create the notification, you probably did something like `NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, ...)`. The `NOTIFICATION_ID` that you passed as first parameter to the `notify` method is the same as the `NOTIFICATION_ID` that you should pass to `notificationManager.cancel`. – Donald Duck Aug 29 '21 at 11:59
44

From: http://developer.android.com/guide/topics/ui/notifiers/notifications.html

To clear the status bar notification when the user selects it from the Notifications window, add the "FLAG_AUTO_CANCEL" flag to your Notification object. You can also clear it manually with cancel(int), passing it the notification ID, or clear all your Notifications with cancelAll().

But Donal is right, you can only clear notifications that you created.

Chuck C.
  • 602
  • 5
  • 5
35

Since no one has posted a code answer to this:

notification.flags = Notification.FLAG_AUTO_CANCEL;

.. and if you already have flags, you can OR FLAG_AUTO_CANCEL like this:

notification.flags = Notification.FLAG_INSISTENT | Notification.FLAG_AUTO_CANCEL;
NPike
  • 13,136
  • 12
  • 63
  • 80
29

Please try methods provided in NotificationManagerCompat.

To remove all notifications,

NotificationManagerCompat.from(context).cancelAll();

To remove a particular notification,

NotificationManagerCompat.from(context).cancel(notificationId);
Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
Rohit Suthar
  • 2,635
  • 1
  • 22
  • 27
  • 3
    In case anyone is getting stuck on NotificationManager not having a `cancel` method, the `cancel` method is not static, so you need an instance of `NotificationManager` like this: `NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);` Then you can call `notificationManager.cancel(notificationId);` like Rohit Suthar referenced in his answer. `notificationId` is simply the ID you passed into `notificationManager.notify(notificationId, mNotification)` – Mira_Cole Mar 13 '18 at 13:59
8

Starting with API level 18 (Jellybean MR2) you can cancel Notifications other than your own via NotificationListenerService.

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class MyNotificationListenerService extends NotificationListenerService {...}

...

private void clearNotificationExample(StatusBarNotification sbn) {
    myNotificationListenerService.cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
}
Jim Vitek
  • 4,174
  • 3
  • 23
  • 32
7

If you are generating Notification from a Service that is started in the foreground using

startForeground(NOTIFICATION_ID, notificationBuilder.build());

Then issuing

notificationManager.cancel(NOTIFICATION_ID);

does not end up canceling the Notification, and the notification still appears in the status bar. In this particular case, you will need to issue

stopForeground( true );

from within the service to put it back into background mode and to simultaneously cancel the notifications. Alternately, you can push it into the background without having it cancel the notification and then cancel the notification.

stopForeground( false );
notificationManager.cancel(NOTIFICATION_ID);
IanGough
  • 89
  • 1
  • 2
7
 Notification mNotification = new Notification.Builder(this)

                .setContentTitle("A message from: " + fromUser)
                .setContentText(msg)
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.app_icon)
                .setContentIntent(pIntent)
                .build();

.setAutoCancel(true)

when you click on notification, open corresponding activity and remove notification from notification bar

Neeraj Singh
  • 610
  • 9
  • 15
6

I believe the most RECENT and UPDATED for AndroidX and backward compatibility. The best way of doing (Kotlin and Java) this should be done as:

NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)

Or to cancel all notifications is:

NotificationManagerCompat.from(context).cancelAll()

Made for AndroidX or Support Libraries.

Xenolion
  • 12,035
  • 7
  • 33
  • 48
4

If you're using NotificationCompat.Builder (a part of android.support.v4) then simply call its object's method setAutoCancel

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setAutoCancel(true);

Some guys were reporting that setAutoCancel() did not work for them, so you may try this way as well

builder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;

Note that the method getNotification() has been deprecated!!!

sandalone
  • 41,141
  • 63
  • 222
  • 338
  • The question asked how to clear it programmatically. setAutoCancel() clears it when the user clicks on the Notification. http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#setAutoCancel(boolean) – S Fitz Aug 05 '15 at 07:32
  • @SFitz It's not clear from the question what he wants. I understood that he wants to clear notification when a user clicks on it. – sandalone Aug 05 '15 at 10:46
2
    // Get a notification builder that's compatible with platform versions
    // >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            this);
    builder.setSound(soundUri);
    builder.setAutoCancel(true);

this works if you are using a notification builder...

1
   String ns = Context.NOTIFICATION_SERVICE;
  NotificationManager Nmang = (NotificationManager) getApplicationContext()
                                                     .getSystemService(ns);
  Nmang .cancel(getIntent().getExtras().getInt("notificationID"));
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Dhina k
  • 1,481
  • 18
  • 24
1

Actually as answered before starting with API Level 18 you can cancel Notifications posted by other apps differet than your own using NotificationListenerService but that approach will no longer work on Lollipop, here is the way to remove notifications covering also Lillipop API.

if (Build.VERSION.SDK_INT < 21) {
    cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
}
else {
    cancelNotification(sbn.getKey());
}
Alejandro Casanova
  • 3,633
  • 4
  • 31
  • 46
0

All notifications (even other app notifications) can be removed via listening to 'NotificationListenerService' as mentioned in NotificationListenerService Implementation

In the service you have to call cancelAllNotifications().

The service has to be enabled for your application via:

‘Apps & notifications’ -> ‘Special app access’ -> ‘Notifications access’.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Samantha
  • 921
  • 9
  • 12
0

this code worked for me:

public class ExampleReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

    int notificationId = 1;
    notificationManager.cancel(notificationId);
  }
}
Wilson
  • 9,006
  • 3
  • 42
  • 46
0

A function written in Kotlin:

/**
 * Delete the notification
 */
fun delete(context: Context, notificationId: Int) =
    with(NotificationManagerCompat.from(context)) {
        cancel(notificationId)
    }

Or shorter:

fun delete(context: Context, notificationId: Int) = NotificationManagerCompat.from(context).cancel(notificationId)
YektaDev
  • 438
  • 3
  • 11
  • 24
0

To clear notifications on Oreo and greater versions

//Create Notification
     Notification.Builder builder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
                        .setContentTitle(getString(R.string.app_name))
                        .setAutoCancel(true);
    
                Notification notification = builder.build();
                NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                createNotificationChannel(builder, notificationManager);
                mNotificationManager=notificationManager;
                startForeground(1, notification);


    //Remove notification
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    mNotificationManager.deleteNotificationChannel(NOTIFICATION_CHANNEL_ID);
                }
Sumedh Ulhe
  • 667
  • 5
  • 10
-1

If you use OneSignal, you must use one of this:

Specific notification:

OneSignal.removeNotification(mutableNotification.androidNotificationId)

All notifications:

OneSignal.clearOneSignalNotifications()

In OneSignal's java doc says:

For removeNotification

Cancels a single OneSignal notification based on its Android notification integer ID. Use
* instead of Android's {@link NotificationManager#cancel(int)}, otherwise the notification will be restored
* when your app is restarted.

For clearOneSignalNotifications

If you just use
* {@link NotificationManager#cancelAll()}, OneSignal notifications will be restored when
* your app is restarted.
Mete
  • 2,805
  • 1
  • 28
  • 38