2012-09-29 149 views
24

我想更新通知數據,但我發現的唯一方法是使用相同的ID啓動一個新的通知數據。是否可以檢查通知是否可見或取消?

問題是如果原件取消了,我不想提出新的問題。 有沒有辦法判斷通知是否可見或取消?或者只有在通知存在時才更新通知?

回答

29

這是我如何解決它:

private boolean isNotificationVisible() { 
    Intent notificationIntent = new Intent(context, MainActivity.class); 
    PendingIntent test = PendingIntent.getActivity(context, MY_ID, notificationIntent, PendingIntent.FLAG_NO_CREATE); 
    return test != null; 
} 

我這是怎麼生成的通知:

/** 
* Issues a notification to inform the user that server has sent a message. 
*/ 
private void generateNotification(String text) { 

    int icon = R.drawable.notifiaction_icon; 
    long when = System.currentTimeMillis(); 
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
    Notification notification = new Notification(icon, text, 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, MY_ID, notificationIntent, 0); 
    notification.setLatestEventInfo(context, title, text, intent); 

    notification.flags |= Notification.FLAG_AUTO_CANCEL; //PendingIntent.FLAG_ONE_SHOT 

    notificationManager.notify(MY_ID, notification); 
} 
+0

有需要的東西是什麼錯誤。當我在我的'''onResume()''''''if(isNotificationVisible())'''''''''''''''''''''''''' MY_ID);'''之後''finish(); startActivity(getIntent());''我得到一個循環,導致重新啓動我的手機。所以這種方法應該謹慎對待...... – maysi

+5

不適合我。這對我來說總是如此。 – Saket

+1

在Android 4.3中沒有適用於我。 'PendingIntent'在我駁回通知後甚至在我殺了整個應用程序之後停滯不前。只有重新啓動手機才能擺脫它。另外,'setLatestEventInfo()'似乎不再存在,所以我只是使用'setContentIntent()'來代替。 – Sam

1

我認爲你可以使用的Notification類。

我記得在我的一個應用程序中,當用戶取消通知或通知托盤被清除時,我用它來激活廣播(自定義廣播)。

1

deleteIntent另一種是已被證明在自己的應用程序有益如下:

基本上,你創建一個意圖,你的通知開始IntentService(或任何其他服務),並在onHandleIntent你可以設置表示通知是否有效的標誌。
當用戶點擊通知(contentIntent)和/或用戶從列表中清除(deleteIntent)時,您可以設置此意圖。

爲了說明這一點,下面是我在自己的應用程序中所做的。當建立通知我設置

Intent intent = new Intent(this, CleanupIntentService.class); 
Notification n = NotificationCompat.Builder(context).setContentIntent(
     PendingIntent.getActivity(this, 0, intent, 0)).build(); 

當通知被竊聽,我CleanupIntentService推出時,設置一個標誌(在服務創建的通知):

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    super.onCreate(); // If removed, onHandleIntent is not called 
    return super.onStartCommand(intent, flags, startId); 
} 


@Override 
protected void onHandleIntent(Intent intent) { 
    OtherService.setNotificationFlag(false); 
} 
6

薩拉姆。 如果您使用API >= 23可以用這個方法來獲得活動的通知:

StatusBarNotification[] notifications = mNotificationManager.getActiveNotifications(); 
for (StatusBarNotification notification : notifications) { 
    if (notification.getId() == 100) { 
    // Do something. 
    } 
}