NullPointerException NullPointerException - 3 months ago 5
Android Question

Intent.FLAG_ACTIVITY_CLEAR_TOP destroys the destination activity. How to avoid?

I'm trying to return back to an activity which is in the activity stack, deleting all the activitys between the current one and the destination activity.

I Readed that this is the way to achieve it:

Intent i = new Intent(SettingsActivity.this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);


Supposedly it will finish all the activities between the current and the destination, but also is destroying the destination activity.

This is not the behaviour I was looking for. I need to avoid the destruction of the destination activity. It should resume itself instead of being destroyed and recreated.

How can that be achieved?

Answer

You need to add FLAG_ACTIVITY_SINGLE_TOP like this:

Intent i = new Intent(SettingsActivity.this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);

When you use FLAG_ACTIVITY_CLEAR_TOP, Android removes all activities on top of the target Activity including the existing instance of the target Activity and then creates a new instance of the target Activity. If you want to use the existing instance of the target Activity, you need to also specify FLAG_ACTIVITY_SINGLE_TOP.

Comments