簡體   English   中英

如何在點擊后正確清除所有通知?

[英]How to properly clear all notification once clicked?

我在通知欄上發送了一些通知,我希望在點擊其中一個通知時清除所有通知。 現在我通過使用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?
}

我的解決方案是在onResume()上調用它。

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

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

您應該使用發送廣播的待處理意圖,然后放置將取消所有通知的廣播接收器。 最好記住所有通知ID並逐個刪除它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM