當使用Notification通知,使用PendingIntent延遲意圖來打開Activity,顯示通知的詳情。
若有多個通知到來,但意圖Intent等都是一樣的,隻是通知的內容不同時,發現多次打開的通知詳情Activity,
顯示的數據居然是第一次的數據,數據沒有更新。
比如顯示代碼: www.aiwalls.com
[java]
//彈出應用自己的通知,在通知欄中顯示xx回復的短信結果
private void popNotification(Context context, SmsMsg smsMsg) {
String body = smsMsg.getBody();
String promptContent = null;
if(null!=body&&body.length()>10){
promptContent = body.substring(0, 10);
}else{
promptContent = body;
}
CharSequence charDateTime = DateFormat.format("yyyy-MM-dd kk:mm:ss", new Date(smsMsg.getTime()));
//獲取 NotificationManager
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//創建一個Notification對象
Notification n = new Notification(R.drawable.ic_launcher, "xx短信提醒", System.currentTimeMillis());
n.flags = Notification.FLAG_AUTO_CANCEL; //通知被點擊後,可自動消失
n.defaults |= Notification.DEFAULT_SOUND; //通知到達時發出默認音樂
n.defaults |= Notification.DEFAULT_VIBRATE; //通知到達時發出默認振動
Intent readMsgIntent = new Intent(context,SmsReadActivity.class);
readMsgIntent.putExtra("SmsMsg", smsMsg); //將收到的短信,攜帶到activity中
readMsgIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //在服務中開啟一個Activity要放此標記
//PendingIntent.FLAG_UPDATE_CURRENT 處理當intent攜帶不同的數據時,activity可以get出不同數據。
PendingIntent pi = PendingIntent.getActivity(context, 300, readMsgIntent, 0); //用戶點擊後開啟readMsgIntent指定的activity
n.setLatestEventInfo(context, "xx短信提醒 "+charDateTime, promptContent, pi);
nm.notify(10, n);
}
問題出現的代碼就是:
PendingIntent pi = PendingIntent.getActivity(context, 300, readMsgIntent, 0);
需要將0改成PendingIntent.FLAG_UPDATE_CURRENT
即改成:PendingIntent pi = PendingIntent.getActivity(context, 300, readMsgIntent, PendingIntent.FLAG_UPDATE_CURRENT); //用戶點擊後開啟readMsgIntent指定的activity
根據API對FLAG_UPDATE_CURRENT的解釋如下:
Flag for use with getActivity, getBroadcast, andgetService: if the described PendingIntent already exists, then keep it but its replace its extra data with what is in this new Intent. This can be used if you are creating intents where only the extras change, and don't care that any entities that received your previous PendingIntent will be able to launch it with your new extras even if they are not explicitly given to it.