【发布时间】:2013-08-04 23:16:02
【问题描述】:
我的MainActicity 以Intent 开头,Intent 有一个额外的boolean isNextWeek。
我的RefreshService 生成一个Notification,当用户点击它时,它会启动我的MainActivity。
看起来像这样:
Log.d("Refresh", "RefreshService got: isNextWeek: " + String.valueOf(isNextWeek));
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.putExtra(MainActivity.IS_NEXT_WEEK, isNextWeek);
Log.d("Refresh", "RefreshService put in Intent: isNextWeek: " + String.valueOf(notificationIntent.getBooleanExtra(MainActivity.IS_NEXT_WEEK,false)));
pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
builder = new NotificationCompat.Builder(this).setContentTitle("Title").setContentText("ContentText").setSmallIcon(R.drawable.ic_notification).setContentIntent(pendingIntent);
notification = builder.build();
// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(NOTIFICATION_REFRESH, notification);
如您所见,notificationIntent 应该有 booleanextra IS_NEXT_WEEK,其值为 isNextWeek,它被放入 PendingIntent。
当我现在点击这个Notification 时,我总是得到false 作为isNextWeek 的值
这是我在MainActivity 中获取值的方式:
isNextWeek = getIntent().getBooleanExtra(IS_NEXT_WEEK, false);
日志:
08-04 00:19:32.500 13367-13367/de.MayerhoferSimon.Vertretungsplan D/Refresh: MainActivity sent: isNextWeek: true
08-04 00:19:32.510 13367-13573/de.MayerhoferSimon.Vertretungsplan D/Refresh: RefreshService got: isNextWeek: true
08-04 00:19:32.510 13367-13573/de.MayerhoferSimon.Vertretungsplan D/Refresh: RefreshService put in Intent: isNextWeek: true
08-04 00:19:41.990 13367-13367/de.MayerhoferSimon.Vertretungsplan D/Refresh: MainActivity.onCreate got: isNextWeek: false
当我直接使用带有“sNextValue”的Intent 启动MainActivity 时,如下所示:
Intent i = new Intent(this, MainActivity.class);
i.putExtra(IS_NEXT_WEEK, isNextWeek);
finish();
startActivity(i);
一切正常,当isNextWeek 为true 时,我得到true。
总是有一个false 值,我做错了什么?
更新
这解决了问题: https://stackoverflow.com/a/18049676/2180161
引用:
我的怀疑是,因为 Intent 中唯一改变的是 额外的,
PendingIntent.getActivity(...)工厂方法是 只需重新使用旧意图作为优化。在 RefreshService 中,尝试:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);见:
http://developer.android.com/reference/android/app/PendingIntent.html#FLAG_CANCEL_CURRENT
更新 2
查看answer below 为什么最好使用PendingIntent.FLAG_UPDATE_CURRENT。
【问题讨论】:
-
PendingIntent.FLAG_CANCEL_CURRENT 为我工作,谢谢
-
为我节省了很多时间。正确答案!
-
您有问题和解决方案:D 很好。我认为您应该将其添加为问题的答案。 +10 秒优于 +5 秒 ;)
-
FLAG_UPDATE_CURRENT 在我的情况下是不够的,因为我的小部件重用了相同的 PendingIntent。我最终将 FLAG_ONE_SHOT 用于很少发生的操作,并保持小部件 PendingIntent 完好无损。
标签: android android-intent android-service android-pendingintent