先描述一下我遇到的問題吧:
後臺服務有可能會發送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值,就可以了。