【问题标题】:Pending Intent from Broadcast Receiver to Activity - old data received从广播接收器到活动的待处理意图 - 接收到旧数据
【发布时间】:2014-04-06 10:37:15
【问题描述】:

我发现了类似的问题,但没有一个解决方案对我有帮助。 我有一个广播接收器拦截短信并将短信文本转发到另一个活动。另一个活动应该显示最新收到的文本。 但另一个活动总是显示应用程序第一次启动后收到的第一条文本。不显示新的短信。

我尝试了什么: 玩弄了 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());

}  
}

这是接收活动的部分:

Intent intent = getIntent();
String message = intent.getStringExtra(SmsReceiver.EXTRA_MESSAGE);
TextView textView = (TextView) findViewById(R.id.tView);
textView.setText(message);

如果您需要更多代码,请告诉我。但我希望这应该足够了,因为它基本上可以工作,只是没有传输新文本。

编辑: 感谢 CommonsWare 这里是解决方案,我刚刚将此方法添加到接收活动中:

@Override
protected void onNewIntent(Intent intent) 
{
    super.onNewIntent(intent);
    TextView textView = (TextView) findViewById(R.id.tView);
    textView.setText(intent.getStringExtra(SmsReceiver.EXTRA_MESSAGE));
}

【问题讨论】:

    标签: android android-activity broadcastreceiver


    【解决方案1】:

    这是接收活动的部分

    如果活动已经在运行,那是错误的Intent。覆盖onNewIntent() 并使用传递给它的IntentgetIntent() 始终返回用于创建活动的Intent,而不是任何将现有实例带回前台的后续活动。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多