Android: Clear Activity Stack

117,391

Solution 1

Most of you are wrong. If you want to close existing activity stack regardless of what's in there and create new root, correct set of flags is the following:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

From the doc:

public static final int FLAG_ACTIVITY_CLEAR_TASK
Added in API level 11

If set in an Intent passed to Context.startActivity(), this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty task, and any old activities are finished. This can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK.

Solution 2

When you call startActivity on the last activity you could always use

Intent.FLAG_ACTIVITY_CLEAR_TOP

as a flag on that intent.

Read more about the flag here.

Solution 3

Here is a simple helper method for starting a new activity as the new top activity which works from API level 4 up until the current version 17:

static void startNewMainActivity(Activity currentActivity, Class<? extends Activity> newTopActivityClass) {
    Intent intent = new Intent(currentActivity, newTopActivityClass);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        intent.addFlags(0x8000); // equal to Intent.FLAG_ACTIVITY_CLEAR_TASK which is only available from API level 11
    currentActivity.startActivity(intent);
}

call it like this from your current activity:

startNewMainActivity(this, MainActivity.class);

Solution 4

Clear Activity Backstate by below code:

Intent intent = new Intent(Your_Current_Activity.this, Your_Destination_Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Done

Solution 5

This decision works fine:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

But new activity launch long and you see white screen some time. If this is critical then use this workaround:

public class BaseActivity extends AppCompatActivity {

    private static final String ACTION_FINISH = "action_finish";

    private BroadcastReceiver finisBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        registerReceiver(finisBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                finish();
            }
        }, new IntentFilter(ACTION_FINISH));
    }

    public void clearBackStack() {
        sendBroadcast(new Intent(ACTION_FINISH));
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(finisBroadcastReceiver);
        super.onDestroy();
    }
}

How use it:

public class ActivityA extends BaseActivity {

    // Click any button
    public void startActivityB() {
        startActivity(new Intent(this, ActivityB.class));
        clearBackStack();
    }
}

Disadvantage: all activities that must be closed on the stack must extends BaseActivity

Share:
117,391
Jay Mayu
Author by

Jay Mayu

I'm iOS / React Native Developer but I also do some Android, HTML5, Laravel and NodeJS. You can follow me at Twitter @mayooresan or connect with me at LinkedIn If you like my answers and posts then probably you will like my blog Mayu's IT Diary

Updated on July 08, 2022

Comments

  • Jay Mayu
    Jay Mayu almost 2 years

    I'm having several activities in my application. and flow is very complicated. When I click the Logout application navigates to login Screen and from there user can exit by cancel button (calling system.exit(0) )

    when I exit or back button, the system invokes an activity from stack :( how can I clear all the activities in the stack when I reach Login screen? calling finish() is not practical as there are so many activities and some activities should no be closed when they are active such as native camera invoking activity.

    validateuser logoutuser = new validateuser();
    logoutuser.logOut();
    Intent loginscreen = new Intent(homepage.this, Login2.class);
    (homepage.this).finish();
    loginscreen.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
    startActivity(loginscreen);
    
  • Jay Mayu
    Jay Mayu over 12 years
    that also doesn't help. I just brings up an activity dat doesn't ended with finish(); :(
  • Jay Mayu
    Jay Mayu over 12 years
    I guess FLAG_ACTIVITY_CLEAR_TOP clears the activities on the top. My problem is activities on the bottom :(
  • David Olsson
    David Olsson over 12 years
    I guess it depends on how the flow actually is. You should read more about it here: developer.android.com/reference/android/content/… and developer.android.com/guide/topics/fundamentals/…
  • David Olsson
    David Olsson over 12 years
    Could be, try to use the flag more or maybe try to improve your flow. Perhaps as singleTask or something similar.
  • Jay Mayu
    Jay Mayu over 12 years
    Thanks for showing correct resources. the mistake i did was closing the Login activity. I should not close it. When the activity loaded first. so when I call it back using Clear_top flag, login activity clears all the activities on the top. since login is the first entrace activity, it clears all the activities started after. so bingo it worked :)
  • AlikElzin-kilaka
    AlikElzin-kilaka almost 12 years
    From the documentation, FLAG_ACTIVITY_CLEAR_TOP clears the stack only if the specific activity "already running in the current task"
  • Davor
    Davor almost 11 years
    Couldn't you than always just use intent.addFlags(0x8000); and simplify that?
  • whlk
    whlk almost 11 years
    As this flag was first introduced in Honeycomb I have no idea what implication it might have on earlier versions. So, this was me being precaucios. But I guess removal of the conditial shouldn't be a problem.
  • Straw Hat
    Straw Hat over 10 years
    you want to add that flag when API level is < 11 then you need to do Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB else intent.addFlags(0x8000); will never added
  • Mahm00d
    Mahm00d almost 10 years
    Worked perfectly. Thanks. Strangely didn't give error with minSDK=9.
  • Muhammad Babar
    Muhammad Babar over 9 years
    @AlikElzin-kilaka good notice. Whats the solution if activity is not already running!
  • David Olsson
    David Olsson over 9 years
    @Umka you should link in that case. "below" is just now, answers my shift in their ordering.
  • Ruchir Baronia
    Ruchir Baronia over 8 years
    I am having the user go by many activities one after the other through intents. Do I need to do anything in order to make sure the app doesn't crash with too many activities on the stack? Thanks!
  • Ruchir Baronia
    Ruchir Baronia over 8 years
    I am having the user go by many activities one after the other through intents. Do I need to do anything in order to make sure the app doesn't crash with too many activities on the stack? Thanks!
  • Ruchir Baronia
    Ruchir Baronia over 8 years
    I am having the user go by many activities one after the other through intents. Do I need to do anything in order to make sure the app doesn't crash with too many activities on the stack? Thanks!
  • Hiren Patel
    Hiren Patel over 8 years
    @RuchirBaronia, If you go A -> B -> C -> D -> E -> F -> G -> H, now H -> I you write my code than I will be Last Activity after then you press Back button app will close because app has no backstate activity, hope this will help you.
  • Ruchir Baronia
    Ruchir Baronia over 8 years
    Do I need to do that though? What will happen if I never clean activity stack?
  • Cynichniy Bandera
    Cynichniy Bandera over 8 years
    Frankly I never used this functionality, resurrect after crash, etc., and rather focused on fixing the issues that caused crash )
  • Hiren Patel
    Hiren Patel over 8 years
    @RuchirBaronia, Backpress: H -> G -> F -> E -> D -> C -> B -> A
  • sealskej
    sealskej over 7 years
    Same functionality also provides IntentCompat.makeRestartActivityTask from support library.
  • Sagar
    Sagar almost 6 years
    But some time it shows white screen while calling new activity. Ho to solve this?
  • Sagar
    Sagar almost 6 years
    why you are using both this.finish() and setFlags() also to clear current activity ?
  • Farid
    Farid over 5 years
    Adding Intent.FLAG_ACTIVITY_CLEAR_TOP restarts the application and then exits totally. I haven't added any flag to activities explicitly tho. What could be the problem?
  • Farid
    Farid over 5 years
    Adding only those two flags leaves activity stack track behind (starts on top of the previous one), then added Intent.FLAG_ACTIVITY_CLEAR_TOP which simply restarts the application and then exits totally. I haven't added any flag to activities explicitly tho. What could be the problem?
  • TheRealChx101
    TheRealChx101 over 5 years
    Doesn't send to work with singleInstance launchMode activities
  • nibbana
    nibbana about 5 years
    One of the best beginnings: "Most of you are wrong."
  • Mithu
    Mithu about 4 years
    what will happen if I use the code in MainActivity onresume() then come back to mainactivity from 2nd activity onbackpress