我发现了类似的问题,但没有一个解决方案对我有帮助。 我有一个广播接收器拦截短信并将短信文本转发到另一个 Activity 。其他 Activity 应显示最新收到的文本。 但另一个 Activity 是始终显示应用程序首次启动后收到的第一个文本。新短信不会显示。
我尝试过的: 尝试了 Pending Intent 的参数(唯一的随机整数和所有 4 个更新选项)- 到目前为止没有帮助。
PendingIntent contentIntent = PendingIntent.getActivity(context, **rand.nextInt(50) + 1**, intent, **FLAG_UPDATE_CURRENT**);
这是来自广播接收器的相关代码,每次触发的通知都会显示新的正确文本。
private void showNotification(Context context) {
Intent intent = new Intent(context, DisplayMSG.class);
intent.putExtra(EXTRA_MESSAGE, str);
Random rand = new Random();
PendingIntent contentIntent = PendingIntent.getActivity(context, rand.nextInt(50) + 1, intent, FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("RPT Notification")
.setContentText(str + Integer.toString(n));
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
这是接收 Activity 的部分:
Intent intent = getIntent();
String message = intent.getStringExtra(SmsReceiver.EXTRA_MESSAGE);
TextView textView = (TextView) findViewById(R.id.tView);
textView.setText(message);
如果您需要更多代码,请告诉我。但我希望这应该足够了,因为它基本上可以工作,只是没有传输新文本。
编辑: 感谢 CommonsWare,这里是解决方案,我刚刚将此方法添加到接收 Activity 中:
@Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
TextView textView = (TextView) findViewById(R.id.tView);
textView.setText(intent.getStringExtra(SmsReceiver.EXTRA_MESSAGE));
}
最佳答案
And here's the part from the receiving activity
如果 Activity 已经在运行,则 Intent
是错误的。重写onNewIntent()
并使用传入的Intent
。 getIntent()
始终返回用于创建 Activity 的 Intent
,而不是任何将现有实例带回前台的后续 Intent。
关于android - 从广播接收器到 Activity 的待处理 Intent - 收到旧数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22892873/