Search code examples
javaandroidandroid-activity

How to always return to same activity on back button?


I have a main activity with a menu. The menu items lead to other activities. I am trying to implement it so that when I start a new activity from the menu, upon pressing the back button the app returns to the main activity regardless of how many other activities were previously opened.

I have tried to use the CLEAR_TOP flag but that doesn't do the trick.

menuItem.setOnClickListener(v -> {
        Intent i = new Intent(AppMenuActivity.this, SomeActivity.class);
        overridePendingTransition(0, 0);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
        resideMenu.closeMenu();
    });

Solution

  • From FLAG_ACTIVITY_CLEAR_TOP android documentation:

    FLAG_ACTIVITY_CLEAR_TOP

    public static final int FLAG_ACTIVITY_CLEAR_TOP
    

    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().

    What does it mean?

    • If launch mode of your activity is "multiple/standard/default" AND you do not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created.
    • If launch mode of your activity is not "multiple/standard/default" OR you set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then this Intent will be delivered to the current instance's onNewIntent().

    Because your MainActivity has "default" launch mode and you do not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, so it will be finished and re-created.

    But you want users back to current instance of MainActivity, so you need to set FLAG_ACTIVITY_SINGLE_TOP in the same intent.

    Just change your code from

    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    

    to

    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);