Home » Android » android – Change intent bundle data before an activity is re-created after orientation change

android – Change intent bundle data before an activity is re-created after orientation change

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have a notification that starts my activity and passes a messages using the intent’s putExtra() function. The message is then displayed to the user in the activity’s onCreate function. When the application is restarted due to a orientation change, the message is shown again as it is still in the intent’s bundled data.

How can I remove the extra data?

I tried the following:

Bundle bundle = getIntent().getExtras();
if (bundle.getBoolean("showMessage")) {
    // ... show message that is in bundle.getString("message")
    // remove message
    bundle.remove("showMessage");
}

But the message will still be shown after the orientation changed, seems like the intent used is not the one I changed, but the original one. The only workaround I found is to save the showMessage additionally in onSaveInstanceState().
Is there another way? Or is this the way to go?

How to&Answers:

The (simple) solution is:

Instead of calling

bundle.remove("showMessage");

I now use

getIntent().removeExtra("showMessage");

which works as expected. Seems like getIntent().getExtras() returns a copy, not a reference.

Answer:

Your onSaveInstanceState() approach is the correct answer, AFAIK.