157

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
  • 23,812
  • 38
  • 150
  • 226
  • @GauravVashisth I was just following this solution http://stackoverflow.com/questions/5794506/android-clear-the-back-stack – Archie.bpgc Oct 18 '12 at 06:03
  • @abbas.aniefa That solution i bit complicated. Is that the only way to clear all the back stack. Because i have 30+ Activities so i should write this broadcast code for all of them – Archie.bpgc Oct 18 '12 at 06:04
  • try this then, http://stackoverflow.com/questions/10961481/closing-previous-pages-in-an-application/10961508#10961508 . Using Broadcast is a better solution. – abbas.aniefa Oct 18 '12 at 06:11
  • another approach you can use for logout, once you logout store one flag in sharedpreferences and in each onRestart() method of an activity you can check this variable value if it is set to true you can finish the current activity. so no matter how many activities are open in backgroud. this would finished all your activity. – Hiren Dabhi Oct 18 '12 at 06:25
  • Your original code actually works for API level 11 or greater with a tweak. You just need to put the flags together in a single call: `intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);` I got the answer from this question: http://stackoverflow.com/questions/3473168/clear-the-entire-history-stack-and-start-a-new-activity-on-android – jokeefe Jan 10 '14 at 04:20
  • Possible duplicate of [Android: Clear Activity Stack](https://stackoverflow.com/questions/7075349/android-clear-activity-stack) – Mehdi Dehghani May 19 '18 at 12:10

18 Answers18

380

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.

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
  • 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. – AlikElzin-kilaka Feb 13 '15 at 01:50
  • This does not work for notifications https://stackoverflow.com/questions/24873131/android-clear-task-flag-not-working-for-pendingintent – Sam Sep 09 '17 at 16:40
  • 1
    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? – Red M Jan 10 '18 at 02:55
  • 1
    This will create a new Task for activities – Rohit Feb 01 '19 at 05:19
  • @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. – Rahul Pareta May 08 '20 at 10:36
32

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

Community
  • 1
  • 1
Anup Cowkur
  • 20,443
  • 6
  • 51
  • 84
  • 4
    Is it feasible when you have around 30 activities on history?? – Rakesh Gondaliya May 03 '13 at 10:13
  • 4
    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. – Anup Cowkur May 03 '13 at 10:22
  • 1
    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: http://stackoverflow.com/a/3008684/243709 – Aman Alam May 31 '13 at 12:03
  • This answer is great. You can also use EventBus library to send events to your activities in backstack. https://github.com/greenrobot/EventBus – Stan Jul 29 '15 at 04:02
  • Better to use simple 'Intent.FLAG_ACTIVITY_CLEAR_TOP' flag with intent – Naveen Rao Oct 09 '15 at 06:33
24

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.

Neeraj Sewani
  • 3,952
  • 6
  • 38
  • 55
23

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.

Matt Accola
  • 4,090
  • 4
  • 28
  • 37
10

What worked for me

Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
startActivity(mainIntent);
Mongi Zaidi
  • 1,043
  • 10
  • 15
7

You can try finishAffinity(), it closes all current activities and works on and above Android 4.1

ndsmyter
  • 6,535
  • 3
  • 22
  • 37
Bunny
  • 576
  • 4
  • 19
6

One possible solution what I can suggest you is to add android:launchMode="singleTop" in the manifest for my ProfileActivity. and when log out is clicked u can logoff starting again you LoginActivity. on logout u can call this.

Intent in = new Intent(Profile.this,Login.class);
                in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(in);
                finish();
Android
  • 3,828
  • 9
  • 46
  • 79
  • I did this, what happened is: when i click back button it takes me to the Activty from where i came to ProfileActivity – Archie.bpgc Oct 18 '12 at 07:23
  • 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? – Android Oct 18 '12 at 08:24
  • 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. – user1914692 Jul 08 '13 at 17:52
6

For API 11+ you can use Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK like this:

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

It will totally clears all previous activity(s) and start new activity.

madx
  • 6,723
  • 4
  • 55
  • 59
4

Use the following for activity

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

remove CLEAR_TASK flag for fragment use.

I hope this may use for some people.

Gowthaman M
  • 8,057
  • 8
  • 35
  • 54
Aristo Michael
  • 2,166
  • 3
  • 35
  • 43
  • 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 ;) – LostSoul May 24 '21 at 22:28
4

Advanced, Reuseable Kotlin:

You can set the flag directly using setter method. In Kotlin or is the replacement for the Java bitwise or |.

intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK

If you plan to use this regularly, create an Intent extension function

fun Intent.clearStack() {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

You can then directly call this function before starting the intent

intent.clearStack()

If you need the option to add additional flags in other situations, add an optional param to the extension function.

fun Intent.clearStack(additionalFlags: Int = 0) {
    flags = additionalFlags or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
Gibolt
  • 42,564
  • 15
  • 187
  • 127
  • 1
    Amazing! This should be more upvoted – Thái Quốc Toàn Dec 05 '22 at 04:51
  • Somehow NEW_TASK, CLEAR_TOP, CLEAR_TASK doesn't work for me, for Android 7.1. Back button still returns to the previous activity. The only way of closing that works is ugly, calling finish() on all non-finished activities. Both adding flags and setting flags. Also finishAffinity() and finishAndRemoveTask() doesn't – George Aug 23 '23 at 06:11
3

You can use below method

    fun signOut(context: Context) {
        try {
                val intent = Intent(context, SplashActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
                context.startActivity(intent)
                (context as Activity).finishAffinity()
            }
        } catch (e: Exception) {
            LogUtils.logE("EXCEPTION", e)
        }

    }
Ranajit Sawant
  • 181
  • 1
  • 6
2

I am also facing the same issue..

in the login activity what i do is.

    Intent myIntent = new Intent(MainActivity.this, ActivityLoggedIn.class);
    finish();
    MainActivity.this.startActivity(myIntent);  

on logout

   Intent myIntent = new Intent(ActivityLoggedIn.this, MainActivity.class);
   finish();
   ActivityLoggedIn.this.startActivity(myIntent);

This works well but when i am in the ActivityLoggedIn and i minimize the app and click on the launcher button icon on the app drawer, the MainActivity starts again :-/ i am using the flag

android:LaunchMode:singleTask 

for the MainActivity.

Sujal Mandal
  • 975
  • 1
  • 14
  • 29
2

In API level 11 or greater, use FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK flag on Intent to clear all the activity stack.

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);
Gowthaman M
  • 8,057
  • 8
  • 35
  • 54
S.Sathya Priya
  • 470
  • 1
  • 5
  • 19
2

None of the intent flags worked for me, but this is how I fixed it:

When a user signs out from one activity I had to broadcast a message from that activity, then receive it in the activities that I wanted to close after which I call finish(); and it works pretty well.

Ian Wambai
  • 203
  • 3
  • 19
2

Try this it will work:

Intent logout_intent = new Intent(DashboardActivity.this, LoginActivity.class);
logout_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
logout_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
logout_intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(logout_intent);
finish();
lebelinoz
  • 4,890
  • 10
  • 33
  • 56
Mohammad Adil
  • 503
  • 6
  • 13
1

Just keep

Intent intent = new Intent(ProfileActivity.this,
    LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
startActivity(intent);
Gaurav Vashisth
  • 7,547
  • 8
  • 35
  • 56
1

add to Manifest for your activity android:launchMode="singleTask"

-2

Use this

Intent i1=new Intent(getApplicationContext(),StartUp_Page.class);
i1.setAction(Intent.ACTION_MAIN);
i1.addCategory(Intent.CATEGORY_HOME);
i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i1);
finish();
Gowthaman M
  • 8,057
  • 8
  • 35
  • 54
Prashant Kumar
  • 419
  • 1
  • 5
  • 15