文章前部分来源:http://byandby.iteye.com/blog/1120375
Xml代码
- <activity android:name="SkyfileActivity"
- android:launchMode="singleTask" />
当我们把Activity 启动模式设置为 singleTask 之后 当我们下次 再去 用Intent 启动 这个 Activity 的时候 就不会去调用 onCreate方法 而是去调用onNewIntent()方法 然后把Intent中的数据传给它 , 前几天遇到的问题是 当我 发一个通知给状态栏 然后点击这个通知 自然会执行 PendingIntent 里边的Intent。 但是 在Activity那边的 onNewIntent()方法里边 得到的数据 不是最新的 也就是说 是 第一次的 以后 不管我怎么点通知 它都 是 第一次点击通知得到的数据,当以后再点击通知的时候其实 数据已经变了 但是 onNewIntent()方法总是得不到最新的数据, 无语了很久, 去 农民伯伯翻译组 发问得解 需要给 PendingIntent 加一个 FLAG
Java代码
- PendingIntent contentIntentBegin = PendingIntent.getActivity(
- notificationContext, 0, inStart, PendingIntent.FLAG_UPDATE_CURRENT);
最后一个参数就是 FLAG,这个FLAG 的 意思就是:如果系统中已存在该PendingIntent对象,那么系统将保留该PendingIntent对象,但是会使用新的Intent来更新之前PendingIntent中的Intent对象数据,例如更新Intent中的Extras。这个非常有用,例如之前提到的,我们需要在每次更新之后更新Intent中的Extras数据,达到在不同时机传递给MainActivity不同的参数,实现不同的效果。
就是 Intent里边的数据没更新而已, 很2个问题 搞了很久 才发现原来加个FLAG 就行了,有点伤不起了。!!
代码片段
Java代码
- public void showNotiMessageBegin(String message, int requestCode,
- String itemid) {
- notification = new Notification(R.drawable.skyfile_upload_noti,
- message, System.currentTimeMillis());
- if (requestCode == 1 && notification.contentIntent == null) {
- int index = itemid.lastIndexOf("/");
- final String backPath1 = itemid
- .substring(0, index == 0 ? 1 : index);
-
- Intent inStart = new Intent(notificationContext, SkyfileActivity.class);
- inStart.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- inStart.setData(Uri.parse(MetaDataView.class.getName()));
- inStart.putExtra(MetaDataView.BUNDLE_PATH, backPath1);
- PendingIntent contentIntentBegin = PendingIntent.getActivity(
- notificationContext, 0, inStart, PendingIntent.FLAG_UPDATE_CURRENT);
- notification.contentIntent = contentIntentBegin;
- notification.flags |= Notification.FLAG_AUTO_CANCEL;
- notification.setLatestEventInfo(notificationContext,
- UPLOATTITLE, message, contentIntentBegin);
- notificationMgr.notify(1, notification);
- } else {
- notification.contentIntent.cancel();
- }
- }
本人另注:其实如果多注意下PendingIntent的文档,就应该明白这里应该用PendingIntent.FLAG_UPDATE_CURRENT。
如果我在从系统中提取一个PendingIntent,而系统中有一个和你描述的PendingIntent对等的PendingInent, 那么系统会直接返回和该PendingIntent其实是同一token的PendingIntent,而不是一个新的token的PendingIntent。如果我们使用了FLAG_UPDATE_CURRENT的话,新的Intent会更新之前PendingIntent中的Intent对象数据,当然也会更新Intent中的Extras。
关于PendingIntent的更多内容请参照《PendingIntent详解》
注意:两个PendingIntent对等是指它们的operation一样, 且其它们的Intent的action, data, categories, components和flags都一样。但是它们的Intent的Extra可以不一样。