如何正确清除所有通知,一旦它们被点击?

32

我在通知栏发送了几个通知,当其中一个通知被点击时,我希望清除所有通知。目前,我通过使用Flag逐个清除通知。我知道 notificationManager.cancelAll() 可以清除所有通知,但我应该把它放在哪里才能在其中一个通知被点击后触发。

 private static void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name); 
    Intent notificationIntent = new Intent(context, MainActivity.class);

    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
            Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent =
            PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(msgid, notification);  
    //notificationManager.cancelAll(); //i wan to clear all when the notification is clicked, where should i put this line?
}
2个回答

90

我的解决方案是在onResume()中调用它。

@Override
protected void onResume() {
super.onResume();

// Clear all notification
NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nMgr.cancelAll();
} 

3
试试这个:NotificationManagerCompat.from(this).cancelAll();它可以取消所有通知。 - Abilash

1

您应该使用一个待处理的意图,发送广播,然后放置一个广播接收器来取消所有通知。最好记下所有通知ID并逐个删除它们。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接