Android: Remove all the previous activities from the back stack

165,584

Solution 1

The solution proposed here worked for me:

Java

Intent i = new Intent(OldActivity.this, NewActivity.class);
// set the new task and clear flags
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);

Kotlin

val i = Intent(this, NewActivity::class.java)
// set the new task and clear flags
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(i)

However, it requires API level >= 11.

Solution 2

Here is one solution to clear all your application's activities when you use the logout button.

Every time you start an Activity, start it like this:

Intent myIntent = new Intent(getBaseContext(), YourNewActivity.class);
startActivityForResult(myIntent, 0);

When you want to close the entire app, do this:

setResult(RESULT_CLOSE_ALL);
finish();

RESULT_CLOSE_ALL is a final global variable with a unique integer to signal you want to close all activities.

Then define every activity's onActivityResult(...) callback so when an activity returns with the RESULT_CLOSE_ALL value, it also calls finish():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(resultCode)
    {
    case RESULT_CLOSE_ALL:
        setResult(RESULT_CLOSE_ALL);
        finish();
    }
    super.onActivityResult(requestCode, resultCode, data);
}

This will cause a cascade effect that closes all your activities.

This is a hack however and uses startActivityForResult in a way that it was not designed to be used.

Perhaps a better way to do this would be using broadcast receivers as shown here:

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activites

See these threads for other methods as well:

Android: Clear the back stack

Finish all previous activities

Solution 3

To clear the activity stack completely you want to create a new task stack using TaskStackBuilder, for example:

Intent loginIntent = LoginActivity.getIntent(context);
TaskStackBuilder.create(context).addNextIntentWithParentStack(loginIntent).startActivities();

This will not only create a new, clean task stack, it will also allow for proper functioning of the "up" button if your LoginActivity has a parent activity.

Solution 4

finishAffinity() added in API 16. Use ActivityCompat.finishAffinity() in previous versions. When you will launch any activity using intent and finish the current activity. Now use ActivityCompat.finishAffinity() instead finish(). it will finish all stacked activity below current activity. It works fine for me.

Solution 5

What worked for me

Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
startActivity(mainIntent);
Share:
165,584
Archie.bpgc
Author by

Archie.bpgc

Updated on October 29, 2021

Comments

  • Archie.bpgc
    Archie.bpgc over 2 years

    When i am clicking on Logout button in my Profile Activity i want to take user to Login page, where he needs to use new credentials.

    Hence i used this code:

    Intent intent = new Intent(ProfileActivity.this,
            LoginActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
    

    in the onButtonClick of the Logout button.

    But the problem is when i click device back button on the Login Activity it takes me to the ProfileActivity. I was expecting the application should close when i press device back button on LoginActivity.

    What am i doing wrong?

    I also added android:launchMode="singleTop" in the manifest for my LoginActivity

    Thank You

  • Archie.bpgc
    Archie.bpgc over 11 years
    Its not working. I can still go to the ProfileActivity using back button
  • Archie.bpgc
    Archie.bpgc over 11 years
    I did this, what happened is: when i click back button it takes me to the Activty from where i came to ProfileActivity
  • Android
    Android over 11 years
    This may happen because u came to ProfileActivity by calling a new intent not by calling finish(); How your are coming to ProfileActivity from other activity apart from LoginActivty?
  • Rakesh Gondaliya
    Rakesh Gondaliya about 11 years
    Is it feasible when you have around 30 activities on history??
  • Anup Cowkur
    Anup Cowkur about 11 years
    should be. But if you have 30 activities in history then you might want to consider changing your design. 30 seems like a bit too much and Android might kill them off itself.
  • Aman Alam
    Aman Alam about 11 years
    This seems a poor way of doing it. @RakeshGondaliya 's answer question seems legit. 30 maybe just a number representing a 'high' number of activities. This answer looks better: stackoverflow.com/a/3008684/243709
  • user1914692
    user1914692 almost 11 years
    I am crossing the same question. I think it would not work when the Login intent was destroyed by the system, say due to lack of memroy.
  • Paul Burke
    Paul Burke over 9 years
    This is the best way to do it.
  • AlikElzin-kilaka
    AlikElzin-kilaka over 9 years
    Guys, read the documentation of FLAG_ACTIVITY_CLEAR_TASK.This is the official way to got. No need to change all the activities in the app.
  • Stan
    Stan almost 9 years
    This answer is great. You can also use EventBus library to send events to your activities in backstack. github.com/greenrobot/EventBus
  • GvSharma
    GvSharma almost 9 years
    did you know setFlags and addFlags?
  • Naveen Rao
    Naveen Rao over 8 years
    Better to use simple 'Intent.FLAG_ACTIVITY_CLEAR_TOP' flag with intent
  • Anurag Srivastava
    Anurag Srivastava over 8 years
    finishAffinity() added in API 16. Use ActivityCompat.finishAffinity() in previous version. I works fine for me.
  • The Berga
    The Berga about 8 years
    It's actually ActivityCompat.finishAffinity()
  • Sam
    Sam almost 7 years
    This does not work for notifications stackoverflow.com/questions/24873131/…
  • Red M
    Red M over 6 years
    I have my minAPI = 16, so this is working perfectly fine for me. However, I noticed that the view execution is a bit sluggish with API >21 and smooth with APIs <21. Anyone experiencing the same problem?
  • T.M
    T.M about 6 years
    FLAG_ACTIVITY_NEW_TASK or finishAffinity() didn't work for me. Only this answer solved the purpose.
  • Tgo1014
    Tgo1014 about 6 years
    If I leave the app via back button and return via app icon it opens up in the activity I called that method. So not working for me.
  • Neeraj Sewani
    Neeraj Sewani almost 6 years
    finishAffinity() also finishes the current activity with all the activities present in the back stack of the same affinity.
  • Rohit
    Rohit over 5 years
    This will create a new Task for activities
  • Rahul Pareta
    Rahul Pareta about 4 years
    @kgiannakakis No doubt solution is working if we have only one task(Activity Back stack) but when we have multiple tasks (Activity stack) it's not working. ex- let's say I have four activities for my application A, B, C & D. Suppose I have two Activity back stacks A->B->C(background) & D->A->B(Foreground) and If I call activity A from my current stack(D->A->B) with intent filter what you suggested what will happen it clear my current stack (D->A->B) and open activity A and when I press back it close application but if I press recent app button I can see two back stacks of my App there.
  • LostSoul
    LostSoul about 3 years
    The additional note "remove CLEAR_TASK flag for fragment use" saved me. You are a great soul! Thanks for terminating my 2 hour debug streak ;)