How to use Notification.deleteIntent

2019-01-17 12:04发布

I'm trying to detect when my notification gets cleared. My question directly refers to this answer which outlines what I'm suppose to do. This is how I'm implementing the actions:

// usual Notification initialization here
notification.deleteIntent = PendingIntent.getService(context, 0, new Intent(context, CleanUpIntent.class), 0);
notificationManager.notify(123, notification)

This is the CleanUpIntent class:

class CleanUpIntent extends IntentService {
    public CleanUpIntent() {
        super("CleanUpIntent");
    }

    @Override
    protected void onHandleIntent(Intent arg0) {
        // clean up code
    }
}

Afterwards, I simply launch the notification like I normally would but when I go to test it out (pressing "Clear All Notifications") nothing happens. I inserted a line of code that out print something to LogCat when the IntentService gets started, but nothing ever ran. Is this how I'm suppose to use Notification.deleteIntent?

4条回答
啃猪蹄的小仙女
2楼-- · 2019-01-17 12:19

You should use getBroadcast methode instead getService and should register receiver for specific Action.

查看更多
SAY GOODBYE
3楼-- · 2019-01-17 12:26

An explicit receiver is not required. deleteIntent will be called automatically while pressing the clear button.

查看更多
再贱就再见
4楼-- · 2019-01-17 12:31

What you need to do is register a BroadcastReceiver (probably in your AndroidManifest.xml or alternatively using registerReceiver in a Service) and then set deleteIntent to be an Intent that will be caught by that receiver.

查看更多
我只想做你的唯一
5楼-- · 2019-01-17 12:36

sample code which will be called whenever user clears the notification, hope it will help you .

 ....
 notificationBuilder.setDeleteIntent(getDeleteIntent());
 ....


protected PendingIntent getDeleteIntent()
 {
    Intent intent = new Intent(mContext, NotificationBroadcastReceiver.class);
    intent.setAction("notification_cancelled");
    return PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}

NotificationBroadcastReceiver.java

@Override
    public void onReceive(Context context, Intent intent)
    {
        String action = intent.getAction();
        if(action.equals("notification_cancelled"))
        {
            // your code
        }
    }

AndroidManifiest.xml

 <receiver android:name=".NotificationBroadcastReceiver">
                <intent-filter>
                    <action android:name="notification_cancelled"/>
                </intent-filter>
            </receiver>
查看更多
登录 后发表回答