我有一个广播接收器,它在接收到某些内容后,将创建一个待处理的意图,将其与一些数据打包,并使用它通过 NotificationManager 创建一个通知。在待处理意图中指定的活动,当 NotificationManager 恢复活动时,始终会读取原始待处理意图的数据——当后续 onReceive() 从广播接收器设置时,它永远不会读取任何新数据。这是广播接收器的片段:
public void onReceive( Context context, Intent intent ) {
String action = intent.getAction();
if( action.equals( "someaction" ) ) {
long now = System.currentTimeMillis();
int icon = R.drawable.icon;
CharSequence tickerText = context.getString( R.string.tickerText );
CharSequence contentTitle = context.getString( R.string.contentTitle );
CharSequence contentText = context.getString( R.string.contentText );
Intent notificationIntent = new Intent( context, MyActivity.class );
Log.d( TAG, "Creating notification with data = " + intent.getStringExtra( "somestring" ) );
notificationIntent.putExtra( "somestring", intent.getStringExtra( "somestring" ) );
notificationIntent.addFlags( Intent.FLAG_ACTIVITY_SINGLE_TOP );
notificationIntent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
PendingIntent contentIntent = PendingIntent.getActivity( context, 0, notificationIntent, 0 );
Notification notification = new Notification( icon, tickerText, now );
NotificationManager notificationmgr = (NotificationManager)context.getSystemService( Context.NOTIFICATION_SERVICE );
notification.flags |= Notification.FLAG_AUTO_CANCEL |
Notification.DEFAULT_SOUND |
Notification.DEFAULT_VIBRATE;
notification.setLatestEventInfo( context, contentTitle, contentText, contentIntent );
notificationmgr.cancelAll();
notificationmgr.notify( 0, notification );
}
}
这是活动的内容:
protected void onStart() {
super.onStart();
Intent intent = getIntent();
String somestring = intent.getStringExtra( "somestring" );
Log.d( TAG, "onStart(), somestring = " + somestring );
}
protected void onResume() {
super.onResume();
Intent intent = getIntent();
String somestring = intent.getStringExtra( "somestring" );
Log.d( TAG, "onResume(), somestring = " + somestring );
}
protected void onNewIntent( Intent intent ) {
Log.d( TAG, "onNewIntent(), intent = " + intent );
super.onNewIntent( intent );
setIntent( intent );
}
所以这里是这样的场景:从主屏幕,我的接收器接收到一些意图,比如说,somestring设置为“hello world”。通知栏显示通知,我向下滑动通知栏,然后点击通知以启动(创建或恢复)活动。该活动正确读出“hello world”。我将活动留在前台或使用主页键将其置于后台。我的广播接收器第二次接收到,比如说,“你好”作为somestring。它再次创建通知,这次使用“hello again”,除了通过通知恢复活动时,我在调试中看到getIntent() 和onNewIntent () 都没有反映 somestring 的更新值(即“你好”)。也就是说,它仍然保留着“hello world”的旧值。
有任何想法吗?我似乎找不到强制更新意图数据的方法。任何帮助表示赞赏;提前致谢。