How to dismiss notification after action has been clicked

AndroidActionAndroid Notifications

Android Problem Overview


Since API level 16 (Jelly Bean), there is the possibility to add actions to a notification with

builder.addAction(iconId, title, intent);

But when I add an action to a notification and the action is pressed, the notification is not going to be dismissed. When the notification itself is being clicked, it can be dismissed with

notification.flags = Notification.FLAG_AUTO_CANCEL;

or

builder.setAutoCancel(true);

But obviously, this has nothing to with the actions associated to the notification.

Any hints? Or is this not part of the API yet? I did not find anything.

Android Solutions


Solution 1 - Android

When you called notify on the notification manager you gave it an id - that is the unique id you can use to access it later (this is from the notification manager:

notify(int id, Notification notification)

To cancel, you would call:

cancel(int id)

with the same id. So, basically, you need to keep track of the id or possibly put the id into a Bundle you add to the Intent inside the PendingIntent?

Solution 2 - Android

Found this to be an issue when using Lollipop's Heads Up Display notification. See design guidelines. Here's the complete(ish) code to implement.

Until now, having a 'Dismiss' button was less important, but now it's more in your face.

heads up notification

Building the Notification

int notificationId = new Random().nextInt(); // just use a counter in some util class...
PendingIntent dismissIntent = NotificationActivity.getDismissIntent(notificationId, context);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setPriority(NotificationCompat.PRIORITY_MAX) //HIGH, MAX, FULL_SCREEN and setDefaults(Notification.DEFAULT_ALL) will make it a Heads Up Display Style
        .setDefaults(Notification.DEFAULT_ALL) // also requires VIBRATE permission
        .setSmallIcon(R.drawable.ic_action_refresh) // Required!
        .setContentTitle("Message from test")
        .setContentText("message")
        .setAutoCancel(true)
        .addAction(R.drawable.ic_action_cancel, "Dismiss", dismissIntent)
        .addAction(R.drawable.ic_action_boom, "Action!", someOtherPendingIntent);

// Gets an instance of the NotificationManager service
NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

// Builds the notification and issues it.
notifyMgr.notify(notificationId, builder.build());

NotificationActivity

public class NotificationActivity extends Activity {

    public static final String NOTIFICATION_ID = "NOTIFICATION_ID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.cancel(getIntent().getIntExtra(NOTIFICATION_ID, -1));
        finish(); // since finish() is called in onCreate(), onDestroy() will be called immediately
    }

    public static PendingIntent getDismissIntent(int notificationId, Context context) {
        Intent intent = new Intent(context, NotificationActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.putExtra(NOTIFICATION_ID, notificationId);
        PendingIntent dismissIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        return dismissIntent;
    }

}

AndroidManifest.xml (attributes required to prevent SystemUI from focusing to a back stack)

<activity
    android:name=".NotificationActivity"
    android:taskAffinity=""
    android:excludeFromRecents="true">
</activity>

Solution 3 - Android

I found that when you use the action buttons in expanded notifications, you have to write extra code and you are more constrained.

You have to manually cancel your notification when the user clicks an action button. The notification is only cancelled automatically for the default action.

Also if you start a broadcast receiver from the button, the notification drawer doesn't close.

I ended up creating a new NotificationActivity to address these issues. This intermediary activity without any UI cancels the notification and then starts the activity I really wanted to start from the notification.

I've posted sample code in a related post Clicking Android Notification Actions does not close Notification drawer.

Solution 4 - Android

In my opinion using a BroadcastReceiver is a cleaner way to cancel a Notification:

In AndroidManifest.xml:

<receiver 
    android:name=.NotificationCancelReceiver" >
    <intent-filter android:priority="999" >
         <action android:name="com.example.cancel" />
    </intent-filter>
</receiver>

In java File:

Intent cancel = new Intent("com.example.cancel");
PendingIntent cancelP = PendingIntent.getBroadcast(context, 0, cancel, PendingIntent.FLAG_CANCEL_CURRENT);

NotificationCompat.Action actions[] = new NotificationCompat.Action[1];

NotificationCancelReceiver

public class NotificationCancelReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		//Cancel your ongoing Notification
	};
}

Solution 5 - Android

You will need to run the following code after your intent is fired to remove the notification.

NotificationManagerCompat.from(this).cancel(null, notificationId);

NB: notificationId is the same id passed to run your notification

Solution 6 - Android

You can always cancel() the Notification from whatever is being invoked by the action (e.g., in onCreate() of the activity tied to the PendingIntent you supply to addAction()).

Solution 7 - Android

In new APIs don't forget about TAG:

notify(String tag, int id, Notification notification)

and correspondingly

cancel(String tag, int id) 

instead of:

cancel(int id)

https://developer.android.com/reference/android/app/NotificationManager

Solution 8 - Android

Just put this line :

 builder.setAutoCancel(true);

And the full code is :

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.co.in/"));
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
    builder.setContentIntent(pendingIntent);
    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.misti_ic));
    builder.setContentTitle("Notifications Title");
    builder.setContentText("Your notification content here.");
    builder.setSubText("Tap to view the website.");
    Toast.makeText(getApplicationContext(), "The notification has been created!!", Toast.LENGTH_LONG).show();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    builder.setAutoCancel(true);
    // Will display the notification in the notification bar
    notificationManager.notify(1, builder.build());

Solution 9 - Android

Just for conclusion:

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

Intent intent = new Intent(context, MyNotificationReceiver.class);
intent.putExtra("Notification_ID", 2022);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
            context,
            0,
            intent,
            ...);

Notification notification = new NotificationCompat.Builder(...)
...    
.addAction(0, "Button", pendingIntent)
.build();

notificationManager.notify(2022, notification);

and for dismiss the notification, you have two options:

approach 1: (in MyNotificationReceiver)

NotificationManager manager = (NotificationManager)
            context.getSystemService(NOTIFICATION_SERVICE);
    manager.cancel(intent.getIntExtra("Notification_ID", -1));

approach 2: (in MyNotificationReceiver)

NotificationManagerCompat manager = NotificationManagerCompat.from(context);
manager.cancel(intent.getIntExtra("Notification_ID", -1));

and finally in manifest:

<receiver android:name=".MyNotificationReceiver" />

Solution 10 - Android

builder.setAutoCancel(true);

Tested on Android 9 also.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionendowzonerView Question on Stackoverflow
Solution 1 - AndroidKaediilView Answer on Stackoverflow
Solution 2 - AndroidaaronvargasView Answer on Stackoverflow
Solution 3 - AndroidVickiView Answer on Stackoverflow
Solution 4 - AndroidHimanshu KhandelwalView Answer on Stackoverflow
Solution 5 - AndroidHoussin BoullaView Answer on Stackoverflow
Solution 6 - AndroidCommonsWareView Answer on Stackoverflow
Solution 7 - AndroidMalachiaszView Answer on Stackoverflow
Solution 8 - AndroidHanishaView Answer on Stackoverflow
Solution 9 - AndroidAmitView Answer on Stackoverflow
Solution 10 - AndroidrudakovskyView Answer on Stackoverflow