如果 activity 是 运行,则获取额外的意向

Get intent extras if activity is running

我正在努力解决这个问题:我有一些通知,我想将额外的意图传递给 activity,即使应用程序已经 运行。

我在 S.O 上找到的一些解决方案。对我不起作用,例如添加:

android:launchMode="singleTop"

对于清单,我也在使用这个:

notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

就像有人建议的那样。

我的代码是这样的:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(NotificationService.this);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle("New website change.");
mBuilder.setContentText("Changed: " + url);

Intent notificationIntent = new Intent(getContext(), MainActivity.class);
Bundle b = new Bundle();
b.putString("key", url);
notificationIntent.putExtras(b);

notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent intent = PendingIntent.getActivity(getContext(), id, notificationIntent, 0);

mBuilder.setContentIntent(intent);

NotificationManager mNotificationManager = (NotificationManager) getSystemService(NotificationService.this.NOTIFICATION_SERVICE);
mNotificationManager.notify(id, mBuilder.build());

然后在activity里面:

Bundle b = getIntent().getExtras();
if(b != null) {
  url = b.getString("key");
  editText.setText(url);
  webView.loadUrl(url);
  webView.requestFocus();
}

欢迎任何帮助,我会将此应用程序的代码作为开源发布,谢谢。

Bundle b = getIntent().getExtras();

这将始终 return 用于 创建 activity 实例的 Intent

如果 activity 已经存在,并且您正在使用 Intent 标志(例如,FLAG_ACTIVITY_REORDER_TO_FRONT 或清单设置(例如,singleTop)来直接控制回到那个 activity,你需要覆盖 onNewIntent()。传递给那个方法的 Intent 是用来把 activity 带回前景。

覆盖 activity 中的 onNewIntent 方法并在此方法中从包中获取值。

@Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

String yourvalue = getIntent.getExtras.getString("key");

    }