Kevin Richards
Kevin Richards

Reputation: 570

How to cancel notification inside onResume()

My app pushes a notification when a new message arrives. Everything is working fine. When the user clicks the notification, it resumes the Activity as expected, and the notification is cancelled (removed).

However, when a user reopens the app (not through the notification), the notification still remains in the status bar.

So, I want to cancel the notification inside the onResume() method of the Activity.

Here is the code for when the notification is created:

Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
        .setContentTitle(channel + ": Unread messages")
        .setSmallIcon(R.mipmap.ic_launcher)
        .setAutoCancel(true)
        .setContentIntent(intent)
        .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.FLAG_AUTO_CANCEL);
notificationManager.notify(0, notification.build());

Upvotes: 0

Views: 702

Answers (3)

nicopico
nicopico

Reputation: 3636

The first argument in NotificationManager.notify() is an identifier, that you can use to cancel the notification afterwards:

private static final int NOTIFICATION_ID = 0;
...
notificationManager.notify(NOTIFICATION_ID, notification.build());
...
notificationMananger.cancel(NOTIFICATION_ID);

Upvotes: 0

MarkySmarky
MarkySmarky

Reputation: 1629

Just call notificationManager.cancel(id) to remove it. When you show the notification you specify its ID (currently you set 0) - when you want to cancel it you need to use the same id.

Upvotes: 1

Ali Abdolahi
Ali Abdolahi

Reputation: 324

You can use this:

public void clearNotification() {
      NotificationManager notificationManager = (NotificationManager) mContext
        .getSystemService(Context.NOTIFICATION_SERVICE);
      notificationManager.cancel(0);
}

and then, call clearNotification() in onResume() mehtod.

in above code, 0 is your NOTIFICATION_ID.

Upvotes: 1

Related Questions