Android: remove notification from notification bar - android

I have created an application and with an event I manage to add notification in android notification bar. Now I need sample how to remove that notification from notification bar on an event ??

You can try this quick code
public static void cancelNotification(Context ctx, int notifyId) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns);
nMgr.cancel(notifyId);
}

This is quite simple. You have to call cancel or cancelAll on your NotificationManager. The parameter of the cancel method is the ID of the notification that should be canceled.
See the API: http://developer.android.com/reference/android/app/NotificationManager.html#cancel(int)

You can also call cancelAll on the notification manager, so you don't even have to worry about the notification ids.
NotificationManager notifManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifManager.cancelAll();
EDIT : I was downvoted so maybe I should specify that this will only remove the notification from your application.

this will help:
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancelAll();
this should remove all notifications made by the app
and if you create a notification by calling
startForeground();
inside a Service.you may have to call
stopForeground(false);
first,then cancel the notification.

simply set setAutoCancel(True) like the following code:
Intent resultIntent = new Intent(GameLevelsActivity.this, NotificationReceiverActivityAdv.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
GameLevelsActivity.this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getApplicationContext()).setSmallIcon(R.drawable.icon)
.setContentTitle(adv_title)
.setContentText(adv_desc)
.setContentIntent(resultPendingIntent)
//HERE IS WHAT YOY NEED:
.setAutoCancel(true);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(547, mBuilder.build());`

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't work canceling the Notification & notification still appears in the status bar. In this particular case, you will solve these by 2 ways:
1> Using stopForeground( false ) inside service:
stopForeground( false );
notificationManager.cancel(NOTIFICATION_ID);
2> Destroy that service class with calling activity:
Intent i = new Intent(context, Service.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
if(ServiceCallingActivity.activity != null) {
ServiceCallingActivity.activity.finish();
}
context.stopService(i);
Second way prefer in music player notification more because thay way not only notification remove but remove player also...!!

A short one Liner of this is:
NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)
Or to cancel all notifications is:
NotificationManagerCompat.from(context).cancelAll()
Made for AndroidX or Support Libraries.

Please try this,
public void removeNotification(Context context, int notificationId) {
NotificationManager nMgr = (NotificationManager) context.getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
nMgr.cancel(notificationId);
}

Use the NotificationManager to cancel your notification. You only need to provide your notification id
mNotificationManager.cancel(YOUR_NOTIFICATION_ID);
also check this link
See Developer Link

NotificationManager.cancel(id) is the correct answer. Yet you can remove in Android Oreo and later notifications by deleting the whole notification channel. This should delete all messages in the deleted channel.
Here is the example from the Android documentation:
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// The id of the channel.
String id = "my_channel_01";
mNotificationManager.deleteNotificationChannel(id);

It will help you
private var notificationManager = NotificationManagerCompat.from(this)
notificationManager.cancel("your_notification_id")
If you start notification foreground like this
startForeground("your_notification_id",notification.build())
Then you should stop foregroundservice also
notificationManager.cancel("your_notification_id")
stopForeground(true)

On Android API >=23 you can do somehting like this to remove a group of notifications.
for (StatusBarNotification statusBarNotification : mNotificationManager.getActiveNotifications()) {
if (KEY_MESSAGE_GROUP.equals(statusBarNotification.getGroupKey())) {
mNotificationManager.cancel(statusBarNotification.getId());
}
}

Just call ID:
public void delNoti(int id) {((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(id);}

Related

NotificationManager Using Clear All Notification [duplicate]

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?
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.
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.
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;
Please try methods provided in NotificationManagerCompat.
To remove all notifications,
NotificationManagerCompat.from(context).cancelAll();
To remove a particular notification,
NotificationManagerCompat.from(context).cancel(notificationId);
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());
}
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);
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
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.
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!!!
// 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...
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());
}
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager Nmang = (NotificationManager) getApplicationContext()
.getSystemService(ns);
Nmang .cancel(getIntent().getExtras().getInt("notificationID"));
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’.
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);
}
}
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)
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.
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);
}

issues in clearing notifications in Android [duplicate]

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?
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.
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.
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;
Please try methods provided in NotificationManagerCompat.
To remove all notifications,
NotificationManagerCompat.from(context).cancelAll();
To remove a particular notification,
NotificationManagerCompat.from(context).cancel(notificationId);
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());
}
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);
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
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.
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!!!
// 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...
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());
}
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager Nmang = (NotificationManager) getApplicationContext()
.getSystemService(ns);
Nmang .cancel(getIntent().getExtras().getInt("notificationID"));
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’.
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);
}
}
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)
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.
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);
}

how to Hide notification after tap in android application

This is the code that gives notification on start of service
NotificationCompat.Builder mbuild = new NotificationCompat.Builder(getApplicationContext());
Intent in = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent resultIN = PendingIntent.getActivity(getApplicationContext(),code,in,NOTIFICATION_COUNT); mbuild.setSmallIcon(R.drawable.images1);
mbuild.setContentText(NOTIFICATION_COUNT +" New Message");
mbuild.setContentIntent(resultIN); //mbuild.addAction(R.drawable.notifications,NOTIFICATION_COUNT +"New Messages",resultIN);
NotificationManager nmagr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nmagr.notify(1, mbuild.build());
everyting is working correct ..the code opens the target activity but the notification still stays there in the notification bar.
i have tried useing mbuil.setautocancel(true); but its doing nothing
try this
NotificationManager nmagr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification=mbuild.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;
nmagr.notify(1,notification);
You didn't set setAutoCancel(true)
Just set this
mbuild.setAutoCancel(true)
or
mbuild.getNotification().flags |= Notification.FLAG_AUTO_CANCEL
Updated
You can also try below code.
NotificationManager mgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
mgr.cancel(1); // here is "1" is your notification id which you set at "nmagr.notify(1, mbuild.build());"
write above code in your onCreate() method of MainActivity.class.
NotificationManager notification_manager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notification_manager.cancel(NOTIFICATION_ID);
Just an update to anyone doing this with NotificationCompat and / or using the Notificaitoncompat.Builder.
This is how I did mine :
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle(title);
/* your own code here */
builder.setAutoCancel(true);
Notification notification = builder.build();
NotificationManagerCompat.from(this).notify(0,notification);
It is important to note that if you use a pending intent to redirect the user to a specific intent in your app, this will also call the pending intent.
As per the documentation :
Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel. The PendingIntent set with setDeleteIntent will be broadcast when the notification is canceled.

How do I remove Notification from status bar?

I am displaying a Notification in status bar depending up on my condition. Up to this, it is OK.
Now problem in my application is when I come back to application, still the Notification is displayed in the status bar.
I don't want the Notification when I come back from the application. For this give me some suggestions.
I don't have enough rep to add comment so #Commonware . . . it would be more helpful to future readers if you gave more specific details like telling them to use a
"notification id" when they create the notification and use that ID to cancel the notification.
If you give an answer make it complete or at least provide the full details. These posts are not only meant for the OP it helps others who come across this post as well.
like so
final NotificationManager notificationManager = (NotificationManager) getSystemService (NOTIFICATION_SERVICE);
final Notification notification = new Notification(R.drawable.icon,"A New Message!",System.currentTimeMillis());
notification.defaults=Notification.FLAG_ONLY_ALERT_ONCE+Notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = new Intent(this, AndroidNotifications.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,notificationIntent, 0);
notification.setLatestEventInfo(AndroidNotifications.this, title,message, pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
Then to cancel it you call
notificationManager.cancel(NOTIFICATION_ID);
or you can call
notificationManager.cancelAll();
You can cancel() your own Notifications via the NotificationManager. It is up to you to decide when to cancel() it and when to show it.
notificationManager.cancelAll();
private void cancelNotificationInBar() {
NotificationCreator notification = new NotificationCreator(getApplicationContext());
notification.mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
if (notification.mNotificationManager != null) {
notification.mNotificationManager.cancelAll();
}
}

How to clear a notification in Android

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?
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.
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.
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;
Please try methods provided in NotificationManagerCompat.
To remove all notifications,
NotificationManagerCompat.from(context).cancelAll();
To remove a particular notification,
NotificationManagerCompat.from(context).cancel(notificationId);
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());
}
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);
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
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.
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!!!
// 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...
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());
}
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager Nmang = (NotificationManager) getApplicationContext()
.getSystemService(ns);
Nmang .cancel(getIntent().getExtras().getInt("notificationID"));
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’.
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);
}
}
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)
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.
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);
}

Categories

Resources