如果活动正在运行,则获取意图附加项

3

我遇到了一个问题:我有一些通知,并且我想向一个活动传递意图附加项,即使应用程序已经在运行。

我在这里找到的一些解决方案对我无效,比如添加:

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();
}

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

你想要实现什么并不清楚。 - Brijesh Kumar
我在通知中有一些URL,我想在具有Webview的活动中打开它。如果活动没有运行(即另一个活动正在运行),则通知可以发送其额外信息,而如果活动在前台,则无法获取额外信息(在这种情况下为URL)。 - Mirko Benedetti
http://stackoverflow.com/questions/40021484/fcm-notification-using-android-studio/40021597#comment67322451_40021597 - Rajesh Satvara
如果应用程序在前台,则可以直接向该活动发送带有URL的广播。它将更新您活动中的URL变量。如果在后台,则该过程将按原样工作。 - Brijesh Kumar
2个回答

4
Bundle b = getIntent().getExtras();

这将始终返回用于创建活动实例的Intent

在活动已存在且您正在使用Intent标记(例如,FLAG_ACTIVITY_REORDER_TO_FRONT)或清单设置(例如singleTop)将控制权重新定向到该活动的情况下,您需要覆盖onNewIntent()。传递给该方法的Intent是用于将活动带回前台的Intent


-1
重写活动中的 onNewIntent 方法,并在此方法中从 Bundle 中获取值。
@Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

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

    }

1
你应该在意图字段中寻找额外信息,而不是使用getIntent()方法。 - Anton Kizema

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接