In Android how can i know the current notification id to clear the notification

社会主义新天地 提交于 2019-12-03 08:32:27

You should add a Tag to your notification and then clear you notification by providing correct id and correct tag.

You don't need notification counter if you pass the same id, because when notification sees the same id, it clears old notification and puts a new one, unless you want to show that user received multiple notifications.

private static final String TAG = "YourNotification";
private static final int NOTIFICATION_ID = 101;
private Notification notification;
public NotificationManager notificationManager;

//you can create notification with it's own id and tag, text, etc by passing 
//these variables into the method (int id, String tag, ... etc)

public void createNotification()
{
    notification = new Notification.Builder(context)
                       .setContentTitle("Content title")
                       .setContentText("Content text")
                       .setSmallIcon(R.drawable.your_small_icon)
                       .setLargeIcon(bitmapYourLargeIcon)
                       .setContentIntent(pendingIntent)
                       .addAction(R.drawable.icon, pendingIntentAction)
                       .build();
    notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(TAG, NOTIFICATION_ID, notification);
}

to cancel notification simply use this method:

//clears your notification in 100% cases

public void cancelNotification(int id, String tag)
{
  //you can get notificationManager like this:
  //notificationManage r= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancel(tag, id);
}
oorosco

you need to add this line of code when you create your notification!!!

notification.flags |= Notification.FLAG_AUTO_CANCEL;

This will cancel the notification on click.

Further reading: Open application after clicking on Notification

** Edit, adding an extra to determine if certain notification was clicked pIntent.putExtra("fromNotification", true);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!