Phi*_*lip 0 notifications android android-intent android-activity android-pendingintent
我有一个广播接收器,在收到某些东西后,会创建一个待定的意图,用一些数据打包它,然后用它来用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 );
}
}
Run Code Online (Sandbox Code Playgroud)
这是活动的内容:
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 );
}
Run Code Online (Sandbox Code Playgroud)
所以这就是场景:从主屏幕开始,我的接收器会收到一些意图,例如,某些字符串设置为"hello world".通知栏显示通知,我向下滑动通知栏,然后点击通知以启动(创建或恢复)活动.活动正确地读出"你好世界".我将活动保留在前台或使用主页键将其保留为背景.第二次围绕我的广播接收器接收,比如说,"再次问好"作为一些东西.它再次创造了通知,此时用"你好再次",通过通知恢复活动时除外,我看到在调试既不 getIntent(),也不onNewIntent()反映的更新值somestring(即"再次问候").也就是说,它仍然保持着"你好世界"的旧价值.
有任何想法吗?我似乎找不到强制更新意图数据的方法.任何帮助表示赞赏; 提前致谢.
固定它.在创建挂起的intent时,应该传递PendingIntent.FLAG_UPDATE_CURRENT:PendingIntent contentIntent = PendingIntent.getActivity(context,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);