Home » Android » android – Intent extras remain the same even when updated

android – Intent extras remain the same even when updated

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am trying to pass a small bit of text between Activity instances using an Intent with extras.

This seems to work fine whenever I navigate between them using the back button or navigation in the action bar. However, if I visit the home screen and then relaunch the application, the extras passed are ignored; the second Activity seems to use the old Intent, rather than the new one.

The relevant code:

Source activity

public class ActivityA extends Activity {
    protected void goToResults(String results) {
        Intent intent = new Intent(this, ActivityB.class);
        intent.putExtra(Intent.EXTRA_TEXT, results);
        startActivity(intent);
    }
}

Destination activity

public class ActivityB extends Activity {
    @Override
    public void onResume() {
        super.onResume();
        Bundle extras = getIntent().getExtras();
        String results = extras.getString(Intent.EXTRA_TEXT);
        // etc
    }
 }

I have tried a number of different things, including:

intent.setAction("action-" + UNIQUE_ID);

(as I understand that Intent instances are not compared by content of extras)

PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

(I don’t need PendingIntent, but thought this might force the Intent to update)

Any suggestions for how to force the Intent to show the changed data every time I make the transition from ActivityA -> ActivityB, regardless of whether I’m using the back button or a diversion to the home screen?

How to&Answers:

I remember running into this issue once, we solved it by either adding Intent.FLAG_ACTIVITY_CLEAR_TOP to the intent you are sending:

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

or by implementing the following method into the activity you’re intent is launching:

@Override
protected void onNewIntent(final Intent intent) {
        super.onNewIntent(intent);
        this.setIntent(intent);
}

I’m not 100% sure what fixed it again, believe it was adding the onNewIntent method.
Good luck and let us know.

Answer:

as @Lauw says :

protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    this.setIntent(intent);
}

this.setIntent(intent);

This line solved the problem for me.

Answer:

Also removing intent extras with intent.removeExtra("key") can help to update incoming new extras.

This approach helped for my case, when I was trying to launch app A from app B. Everything worked when app A wasn’t opened, but when app A was already opened, I had to use the removeExtra method to get the updates.