Mirko Benedetti
Mirko Benedetti

Reputation: 81

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.

Upvotes: 3

Views: 1600

Answers (2)

LoveAndroid
LoveAndroid

Reputation: 186

override the onNewIntent method in the activity and getting the value from the bundle in this method.

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

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

    }

Upvotes: -1

CommonsWare
CommonsWare

Reputation: 1006654

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.

Upvotes: 4

Related Questions