我的MainActivity
使用带有名为isNextWeek
的boolean
额外参数的Intent
启动RefreshService
。
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
应该带有布尔值额外信息IS_NEXT_WEEK
,其值为被放置在PendingIntent
中的isNextWeek
。
当我现在点击此Notification
时,isNextWeek
的值总是false
。
这是我在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
当我使用意图(Intent
)并且设置了`isNextValue`属性,直接启动MainActivity
时:
Intent i = new Intent(this, MainActivity.class);
i.putExtra(IS_NEXT_WEEK, isNextWeek);
finish();
startActivity(i);
一切都正常工作,当isNextWeek
为true
时,我得到true
。
我错在哪里,导致总是出现false
的值?
更新
这解决了问题: https://dev59.com/DmMl5IYBdhLWcg3w3aTj#18049676
引用:
我怀疑,由于Intent中唯一更改的是extra,
PendingIntent.getActivity(...)
工厂方法仅仅是为了优化而重新使用旧Intent。在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
请查看下面的答案,解释为什么最好使用
PendingIntent.FLAG_UPDATE_CURRENT
。