private Notification genreNotification(Context context, int icon, String tickerText, String title, String content, Intent intent){ Notification notification = new Notification(icon, tickerText, System.currentTimeMillis()); PendingIntent pendIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); notification.setLatestEventInfo(context, title, content, pendIntent); notification.flags |= Notification.FLAG_AUTO_CANCEL; return notification; } ... mNotificationManager.notify(ID_1, genreNotification(mContext, ICON_RES, notifyText1, notifyTitle1, notifyText1, intent_1)); ... mNotificationManager.notify(ID_2, genreNotification(mContext, ICON_RES, notifyText2, notifyTitle2, notifyText2, intent_2)); ... mNotificationManager.notify(ID_3, genreNotification(mContext, ICON_RES, notifyText3, notifyTitle3, notifyText3, intent_3));
可見ID和Intent都是不同的,產生的PendingIntent分別對應著不同的Intent。但是,你會發覺無論點哪個Notification,傳遞迴來的都是最後被notify的Intent。這裡即intent_3。
找了很久,試了改變PendingIntent的flag也無果,最後還是在這文章裡找到答案(CSDN文章 ),我來總結下:
問題主要出在PendingIntent.getActivity();的第二個參數,API文檔裡雖然說是未被使用的參數(給出的例子也直接寫0的),實際上是通過該參數來區別不同的Intent的,如果id相同,就會覆蓋掉之前的Intent了。所以總是擷取到最後一個Intent。
private Notification genreNotification(Context context, int icon, String tickerText, String title, String content, Intent intent, int id){ Notification notification = new Notification(icon, tickerText, System.currentTimeMillis()); // 問題就在這裡的id了 PendingIntent pendIntent = PendingIntent.getActivity(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT); notification.setLatestEventInfo(context, title, content, pendIntent); notification.flags |= Notification.FLAG_AUTO_CANCEL; return notification; } ... mNotificationManager.notify(ID_1, genreNotification(mContext, ICON_RES, notifyText1, notifyTitle1, notifyText1, intent_1, ID_1)); ... mNotificationManager.notify(ID_2, genreNotification(mContext, ICON_RES, notifyText2, notifyTitle2, notifyText2, intent_2, ID_2)); ... mNotificationManager.notify(ID_3, genreNotification(mContext, ICON_RES, notifyText3, notifyTitle3, notifyText3, intent_3, ID_3));