Android 如果活动正在运行,则获取额外的意图

Android 如果活动正在运行,则获取额外的意图,android,android-intent,notifications,android-pendingintent,Android,Android Intent,Notifications,Android Pendingintent,我正在努力解决这个问题:我有一些通知,我想向活动传递意图附加信息,即使应用程序已经在运行 我在S.O.上找到的一些解决方案不适合我,例如添加: android:launchMode="singleTop" 对于清单,我还使用了以下内容: notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 就像有人建议的那样 我的代码是: NotificationCompat.Builder mBuilder = new Notifica

我正在努力解决这个问题:我有一些通知,我想向活动传递意图附加信息,即使应用程序已经在运行

我在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());
然后在活动中:

Bundle b = getIntent().getExtras();
if(b != null) {
  url = b.getString("key");
  editText.setText(url);
  webView.loadUrl(url);
  webView.requestFocus();
}
欢迎任何帮助,我将以开源方式发布此应用程序的代码,谢谢

Bundle b = getIntent().getExtras();
这将始终返回用于创建活动实例的
意图


如果活动已经存在,并且您正在使用
Intent
标志(例如,
FLAG\u activity\u REORDER\u TO\u FRONT
或清单设置(例如,
singleTop
)将控制返回到该活动,则需要覆盖
onNewIntent()
。传递给该方法的
Intent
是用于将活动恢复到前台的
Intent

覆盖活动中的onNewIntent方法,并在此方法中从捆绑包中获取值

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

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

    }

不清楚您想要实现什么。我在通知中有一些url,我想在活动上打开它,该活动有一个网络视图。如果该活动未运行(即另一个活动正在运行),则通知可以发送其附加内容,而如果该活动位于前台,则无法获取附加内容(在本例中为url).K.如果活动位于前台,则可以将带有url的广播直接发送到活动。它将更新活动中的url变量。如果活动位于后台,则流程将按原样运行。您应该在intent字段中查找额外内容,而不是getIntent()