How to detect if a notification has been dismissed?

天大地大妈咪最大 提交于 2019-12-04 22:21:46

I believe that Notification.deleteIntent is what you are looking for. The doc says:

The intent to execute when the notification is explicitly dismissed by the user, either with the "Clear All" button or by swiping it away individually. This probably shouldn't be launching an activity since several of those will be sent at the same time.

To all those future people out there -- you can register a broadcast receiver to listen for notification delete inents.

Create a new broadcast receiver:

public class NotificationBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (action == null || !action.equals(Config.NotificationDeleteAction)) {
            return;
        }

        // Do some sweet stuff
        int x = 1;
    }
}

Register the broadcast receiver within your application class:

"If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver for most implicit broadcasts (broadcasts that do not target your app specifically)."

Android Documentation.

  registerReceiver(
        new NotificationBroadcastReceiver(),
        new IntentFilter(Config.NotificationDeleteAction)
  );

You probably noticed the static variable Config.NotificationDeleteAction. This is a unique string identifier for your notification. It typically follows the following {namespace}{actionName} convention:

you.application.namespace.NOTIFICATION_DELETE

Set the delete intent on your notification builder:

notificationBuilder
       ...
        .setDeleteIntent(createDeleteIntent())
       ...

Where, createDeleteIntent is the following method:

private PendingIntent createDeleteIntent() {
    Intent intent = new Intent();
    intent.setAction(Config.NotificationDeleteAction);

    return PendingIntent.getBroadcast(
            context,
            0,
            intent,
            PendingIntent.FLAG_ONE_SHOT
    );
}

Your registered broadcast receiver should receive the intent when your notification is dismissed.

You can also use an Activity PendingIntent, which may be simpler to implement if you have an Activity that can handle the dismissal, because you don't have to create and configure a broadcast receiver.

public static final String DELETE_TAG = "DELETE_TAG";

private PendingIntent createDeleteIntent(Context context) {
    Intent intent = new Intent(context, MyActivity.class);
    intent.putExtra(DELETE_TAG, true);

    return PendingIntent.getActivity(
            context,
            0,
            intent,
            PendingIntent.FLAG_ONE_SHOT
    );
}

MyActivity would receive the intent in its onCreate(), and in this example, could look for the DELETE_TAG extra to recognize it.

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