Search code examples
androidandroid-intentnotificationsandroid-pendingintent

Get intent extras if activity is running


I'm struggling with this problem: I have some notifications and I want to pass intent extras to an activity, even if the application is already running.

Some solutions I found here on S.O. didn't work for me, like adding:

android:launchMode="singleTop"

to the manifest, I'm also using this:

notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

like someone suggested.

My code is this:

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

And then inside the activity:

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

Any help will be welcome, I will release this app's code as open source, thanks.


Solution

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

    This will always return the Intent that was used to create the activity instance.

    In cases where the activity already exists, and you are using Intent flags (e.g., FLAG_ACTIVITY_REORDER_TO_FRONT or manifest settings (e.g., singleTop) to direct control back to that activity, you need to override onNewIntent(). The Intent delivered to that method is the Intent that was used to bring the activity back to the foreground.