Search code examples
androidandroid-intentandroid-activityactivity-lifecycleandroid-navigation

How to return to an activity closing the in between activities?


I need to go back to the main activity of my app, but for that, I need to close all the activities in between the current activity and the main activity.

I tried with this:

Intent intent = new Intent(getActivity(), MainMenuActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity( intent );

The problem is that doing this, the main activity is also closed and reopenned, calling to onDestroy() in the main destiny activity. I need to go back to it without closing and reopening it. How to achieve it?


Solution

  • The documentation on FLAG_ACTIVITY_CLEAR_TOP says

    The currently running instance [...] will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent. If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent().

    In your case, I assume that your MainMenuActivity has a "multiple" launch mode. Since you did not set FLAG_ACTIVITY_SINGLE_TOP, it was finished and restarted.

    So if you use

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|FLAG_ACTIVITY_SINGLE_TOP);
    

    then according to the documentation the MainMenuActivity instance will keep its state and onNewIntent() will be called.

    Note: you can use setIntent() to make the Intent which is passed into onNewIntent() "the" Intent of the Activity