先描述一下我遇到的問題吧:
背景服務有可能會發送3種通知資訊,均指向同一個Activity,隻是Intent中所帶的資訊不一樣。當3個通知同時出現時,問題就來了,點選通知,列印Intent所帶的資訊,發現都一樣!
具體看下發送通知的代碼:
private void sendNotification(int id) {
Intent intent = new Intent(BBSService.this, BBSListActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (id == BBS_REPLY_ID) {
intent.putExtra("reply", true);
intent.putExtra("at", false);
intent.putExtra("mail", false);
} else if (id == BBS_AT_ID) {
intent.putExtra("reply", false);
intent.putExtra("at", true);
intent.putExtra("mail", false);
} else if (id == BBS_MAIL_ID) {
intent.putExtra("reply", false);
intent.putExtra("at", false);
intent.putExtra("mail", true);
}
intent.putExtra("id", id);
Notification BBSNotification = new Notification();
BBSNotification.icon = R.drawable.ic_launcher;
BBSNotification.tickerText = "愛郵";
BBSNotification.when = System.currentTimeMillis();
BBSNotification.defaults = Notification.DEFAULT_SOUND;
BBSNotification.defaults |= Notification.DEFAULT_VIBRATE;
BBSNotification.flags |= Notification.FLAG_AUTO_CANCEL;
PendingIntent mobilePi = PendingIntent.getActivity(BBSService.this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (id == BBS_REPLY_ID) {
BBSNotification.setLatestEventInfo(BBSService.this, "論壇消息",
"新回複我的文章件", mobilePi);
} else if (id == BBS_AT_ID) {
BBSNotification.setLatestEventInfo(BBSService.this, "論壇消息",
"新@我的文章", mobilePi);
} else if (id == BBS_MAIL_ID) {
BBSNotification.setLatestEventInfo(BBSService.this, "論壇消息", "新郵件",
mobilePi);
}
notificationManager.notify(id, BBSNotification);
}
通過深入了解,大概明白問題在哪裡了。
PendingIntent.getActivity(Context context, int requestCode, Intent intent, int flags)方法并不能保證每次傳回的PendingIntent都是一個新的。如果這個PendingIntent已經存在,那麼就會按照flags位的設定對intent進行處理,我這裡用的是PendingIntent.FLAG_UPDATE_CURRENT,那麼每次都會更新intent,也就是說如果發送了3個通知,那麼他們所攜帶的intent都會是最後一次更新的那個intent。
明白了問題所在,那麼解決方法就呼之欲出了,隻要保證PengdingIntent的配置不同,那麼getActivity傳回的必然就是新的PendingIntent。這裡把requestCode值定義為id值,就可以了。