Android 通知PendingIntent意图打开Activity,数据无更新

当使用Notification通知,使用PendingIntent延迟意图来打开Activity,显示通知的详情。

若有多个通知到来,但意图Intent等都是一样的,只是通知的内容不同时,发现多次打开的通知详情Activity,

显示的数据居然是第一次的数据,数据没有更新。

比如显示代码:

//弹出应用自己的通知,在通知栏中显示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.

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/f13ee5faea92b8129ccaec392fdc1b99.html