97

How can one remove a notification from an application programmatically, which is called using Pending intent?

I have used to cancel notification using following method:

AlarmManager am=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(Display.this, TwoAlarmService.class);
PendingIntent pi = PendingIntent.getBroadcast(Display.this, AlarmNumber, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.cancel(pi);

But problem is notification which fired already that are not removed from notification bar.

enter image description here

starball
  • 20,030
  • 7
  • 43
  • 238
Jayeshkumar Sojitra
  • 2,501
  • 4
  • 31
  • 44
  • hi i don't know is it possible to remove notification programaticaly , but you can override the old notification with new one that's sure. if is it fullfil your requirement then i can post code for you here. plz reply – Brijesh Patel Oct 09 '13 at 09:50
  • No, actually I have two different notifications and I am already cancelling notification. – Jayeshkumar Sojitra Oct 09 '13 at 09:52

5 Answers5

241

Maybe try this :

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

OR, you can also do this to cancel all notifications in given context:

notificationManager.cancelAll();

See this link to the documentation : NotificationManager

An-droid
  • 6,433
  • 9
  • 48
  • 93
  • 8
    I don't see the point of `if (Context.NOTIFICATION_SERVICE != null)` because that is a String constant and will never be null. – tar Apr 09 '14 at 07:05
  • 8
    you are right this test is useless, i don't know why i did it (deleted it):/ – An-droid Apr 09 '14 at 08:03
  • @Matthieu it worked for be before 4 years... :) Not checked right now. Please let me know if it's not working in any case. – Jayeshkumar Sojitra Aug 17 '18 at 11:11
  • @JayeshSojitra I was just curious which of `cancel(NOTIFICATION_ID)` or `cancelAll()` did the trick. In case your memory went back that far, it's not a big deal :) – Matthieu Aug 17 '18 at 12:31
  • 1
    @Matthieu In my case both worked. If you want to cancel specific one then use cancel(NOTIFICATION_ID) and if you want to cancel all notification then user cancelAll(). – Jayeshkumar Sojitra Aug 17 '18 at 12:35
  • How can I get the `NOTIFICATION_ID`? – Teocci Jun 28 '19 at 00:41
  • NOTIFICATION_ID is the id used at the creation of the notification, it's a parameter you can set at any value – An-droid Aug 05 '19 at 15:10
  • Dear @An-droid I'm using your solution in react-native to remove all the popUps created by firebase it self and just show my own popup, but it doesn't remove the popup. any idea? – Niloufar Oct 22 '19 at 08:40
  • It seems to be a known issue the method would be `removeDeliveredNotification(notifId)` or `removeAllDeliveredNotifications` found in firebase documentation, you can find the opened issues on firebase github – An-droid Nov 28 '19 at 16:59
  • if you start your service in forground then you must use stopForeground(true); for service and then you can use above syntex. – varotariya vajsi Jun 10 '20 at 12:59
  • @Niloufar almost one year after, but in the notification body you can set [a `priority` option](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that determines how the notification is displayed. – Ivan García Topete Aug 18 '20 at 18:26
26

I believe the most RECENT and UPDATED 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
7

Notifications remain visible until one of the following happens:

The user dismisses the notification either individually or by using "Clear All" (if the notification can be cleared). The user clicks the notification, and you called setAutoCancel() when you created the notification. You call cancel() for a specific notification ID. This method also deletes ongoing notifications. You call cancelAll(), which removes all of the notifications you previously issued. If you set a timeout when creating a notification using setTimeoutAfter(), the system cancels the notification after the specified duration elapses. If required, you can cancel a notification before the specified timeout duration elapse

public void cancelNotification() {

    String ns = NOTIFICATION_SERVICE;
    NotificationManager nMgr = (NotificationManager) getActivity().getApplicationContext().getSystemService(ns);
    nMgr.cancel(NOTIFICATION_ID);
}
SilverNak
  • 3,283
  • 4
  • 28
  • 44
Fakhriddin Abdullaev
  • 4,169
  • 2
  • 35
  • 37
3

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’.

Add to manifest:

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:label="Test App" android:name="com.test.NotificationListenerEx" android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
        <intent-filter>
            <action android:name="android.service.notification.NotificationListenerService" />
        </intent-filter>
    </service>

Then in code;

public class NotificationListenerEx extends NotificationListenerService {


public BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationListenerEx.this.cancelAllNotifications();
    }
};


@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    super.onNotificationPosted(sbn);
}

@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
    super.onNotificationRemoved(sbn);
}

@Override
public IBinder onBind(Intent intent) {
    return super.onBind(intent);
}

@Override
public void onDestroy() {
    unregisterReceiver(broadcastReceiver);
    super.onDestroy();
}

@Override
public void onCreate() {
    super.onCreate();
    registerReceiver(broadcastReceiver, new IntentFilter("com.test.app"));
}

After that use the broadcast receiver to trigger the clear all.

As per the above code to trigger the broadcast use;

getContext().sendBroadcast(new Intent("com.test.app"));
Samantha
  • 921
  • 9
  • 12
2

For those who used (via subclass) the Service class and run it using:

final Intent serviceIntent = new Intent(context, YourNotificationService.class);
ContextCompat.startForegroundService(context, serviceIntent);

you can close it like so:

context.stopService(new Intent(context, YourNotificationService.class));
Miko Chu
  • 1,087
  • 14
  • 22