By Martin


2011-04-26 18:03:11 8 Comments

In Android I have some activities, let's say A, B, C.

In A, I use this code to open B:

Intent intent = new Intent(this, B.class);
startActivity(intent);

In B, I use this code to open C:

Intent intent = new Intent(this, C.class);
startActivity(intent);

When the user taps a button in C, I want to go back to A and clear the back stack (close both B and C). So when the user use the back button B and C will not show up, I've been trying the following:

Intent intent = new Intent(this, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
startActivity(intent);

But B and C are still showing up if I use the back button when I'm back in activity A. How can I avoid this?

30 comments

@user2830808 2019-03-15 12:44:55

This is how I solved the problem:

private boolean clearHistoryBackStack = true;

@Override
public final void finish() {
    super.finish();

    if(clearHistoryBackStack)
        finishAffinity();
}

@stevyhacker 2019-02-28 00:18:50

Kotlin example:

      val intent = Intent([email protected], MainActivity::class.java)
      intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
      startActivity(intent)
      finish()

@Mujeeb Rahaman T 2019-02-19 11:33:41

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

@Exigente05 2019-01-23 20:59:52

In kotlin it is almost same like java. Only | symbol is replaced by or text. So, it is written like-

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)

@Sujith Royal 2018-09-12 10:01:37

I found an interesting solution which might help. I did this in my onBackPressed() method.

finishAffinity();
finish();

FinishAffinity removes the connection of the existing activity to its stack. And then finish helps you exit that activity. Which will eventually exit the application.

@PhilipS 2018-03-12 11:56:58

This worked for me with onBackPressed:

public void onBackPressed()
{
    Intent intent = new Intent(ImageUploadActivity.this, InputDataActivity.class);

    Intent myIntent = new Intent(this, ImageUploadActivity.class);
    myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
   finish();
}

@Firzan Shaikh 2017-10-28 06:53:39

Use finishAffinity() to clear all backstack with existing one.

Suppose, Activities A, B and C are in stack, and finishAffinity(); is called in Activity C, 

    - Activity B will be finished / removing from stack.
    - Activity A will be finished / removing from stack.
    - Activity C will finished / removing from stack.

@Guilherme Junqueira Coutinho 2017-09-18 19:37:15

This is a really old answer and i didn't really found a proper solution to it, to the sole purpose of clearing the backStack, i decided to create my own backstack, which is not even a stack tbh, but it doesn't have to be, since we want to clear everything in it anyways;

Theres an overhead of handlind the backstack everytime, but it gave me the control i needed;


First Declare a public static List of Activities (or fragments, whatever you need);

public static ArrayList <Activity> backStack = new ArrayList<>();

And inside all other activity's onCreate method:

MainActivity.backStack.add(this);

And finally, when you want to clear the backstack, simply call:

public static void killBackStack () {
    for (Activity ac : backStack) {
        if (ac != null)
            ac.finish();
    }
}

@Pankaj Talaviya 2017-09-07 05:03:31

Use setFlags() method for clear back side opened all activity close and start yourActvity

Intent intent = new Intent(getApplicationContext(), yourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

@Pankaj Talaviya 2017-03-10 10:10:24

use this code for starting new activity and close or destroy all other acivity stack or back satack...

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

@baswaraj 2016-12-15 14:49:43

Use finishAffinity(); in task C when starting task A to clear backstack activities.

@nuttynibbles 2017-02-03 15:30:13

only this answer works for me. Intent.FLAG_ACTIVITY_CLEAR_TOP and Intent.FLAG_ACTIVITY_NEW_TASK are not required

@Maximus 2011-04-26 18:06:29

It sounds to me like you need to start Activity C from Activity B by using startActivityForResult(). When you click a button in Activity C, call setResult(RESULT_OK) and finish() so Activity C is ended. In Activity B, you could have the onActivityResult() respond by also calling finish() on itself, and you'd then be taken back to Activity A.

@Guillaume Brunerie 2011-04-26 18:10:26

Yes, but if there are 42 activities between A and C, this will be rather tedious. The flag FLAG_ACTIVITY_CLEAR_TOP is supposed to do directly what the OP want.

@Jake Basile 2011-04-26 18:15:18

This would be a less than optimal way of achieving what the OP wants, and as @Guillaume said, it would require code in all of the activities between the root and the top of the stack.

@Maximus 2011-04-26 18:16:22

Duly noted. These are flags I need to learn about apparently.

@Ashish Saini 2016-04-01 07:47:13

Intent.FLAG_ACTIVITY_CLEAR_TOP will not work in this case. Please use (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)

For more detail please check out this documentation.

@Renjith JR 2016-04-01 09:27:34

Either add this to your Activity B and Activity C

android:noHistory="true"

or Override onBackPressed function to avoid back pressing with a return.

@Override
public void onBackPressed() {
   return;
}

@Muhammad Aamir Ali 2013-05-16 07:58:03

Try using

intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

and not

intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

@Tarun 2016-04-19 05:41:16

I tried all solutions and none worked individually for me. My Solution is :

Declare Activity A as SingleTop by using [android:launchMode="singleTop"] in Android manifest.

Now add the following flags while launching A from anywhere. It will clear the stack.

Intent in = new Intent(mContext, A.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK );
startActivity(in);
finish();

@Vipin Yadav 2016-07-12 11:55:21

You can use this example to call your Activity A from Activity C

Intent loout = new Intent(context, LoginActivity.class); loout.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); context.startActivity(loout);

@blackjack 2016-09-27 10:41:58

In manifest

android:launchMode="singleTask"

and

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

@Jaydeep purohit 2016-04-13 12:42:52

If your application has minimum sdk version 16 then you can use finishAffinity()

Finish this activity as well as all activities immediately below it in the current task that have the same affinity.

This is work for me In Top Payment screen remove all back-stack activits,

 @Override
public void onBackPressed() {
         finishAffinity();
        startActivity(new Intent(PaymentDoneActivity.this,Home.class));
    } 

http://developer.android.com/reference/android/app/Activity.html#finishAffinity%28%29

@Dominik Helleberg 2011-06-28 20:38:24

What about adding in manifests file for related activity :

android:noHistory="true"

to the activity definition of B and C ? They will not be added to the backstack. Not sure if that is what you want.

@cracked_all 2013-10-11 19:24:29

this worked just fine for me, the accepted answer did not!

@tbraun 2014-10-03 13:04:57

this solution works! tested on Android 4.4

@carstenbaumhoegger 2014-12-17 20:05:30

thanks man, this solved the last big bug in my app!

@Skynet 2015-03-02 12:26:15

Be very careful while using this - If you are using login with FB or any similar sort of functionality

@Alfie Woodland 2015-03-12 16:32:32

@Skynet Why? What are the problems associated with doing this?

@Skynet 2015-03-13 07:18:01

When you pass control to FB for login from a page with nohistory as true, the FB app does not now where to land after loging the user in, in my case it was returning to the phone home screen and I almost lost my job!

@Tarun 2016-04-19 05:17:40

This does not let an activity addded to backstack....this is not correct solution.

@alicanozkara 2017-01-28 21:49:50

thanks man! you saved my day. this solution works

@GvSharma 2017-10-31 17:36:52

sometimes its not working in Android-7

@Masum 2018-06-26 10:50:21

Exactly i am looking for

@Yannick 2018-11-15 20:29:01

Only thing which worked out for me

@diesel 2012-12-03 20:10:35

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

@Aviel Gross 2015-03-08 06:31:16

With all respect to the CLEAR_TOP flag - this combination is the ONLY one that completely cleared the entire stack and made the new activity the only one in the app. Thank you!

@Yuri Heupa 2015-09-24 01:59:06

What's the diff between this and the accepted answer?

@March3April4 2016-11-06 08:07:27

This was perhaps what I was looking for. Works great!

@Pablo Cegarra 2017-02-16 12:51:40

Thanks, the difference with the accepted answer is that with this flag we dont need to call activity.finish

@Woppi 2017-12-27 11:22:05

With this setup, when I click back, it closes the app.

@Shamsul Arefin Sajib 2018-05-09 13:10:49

FLAG_ACTIVITY_CLEAR_TASK worked perfectly together with NEW_TASK

@MD Danish Ansari 2018-07-25 15:10:56

This should be the accepted answer. Thank you very much.

@Daniel Schuler 2013-05-29 22:58:48

Starting in API 16 (Jelly Bean), you can just call finishAffinity().

Now you can also call ActivityCompat.finishAffinity(Activity activity) with the compatibility library.

Be sure to set taskAffinity in the manifest to a package name unique to that group of activities.

See for more info:
http://developer.android.com/reference/android/support/v4/app/ActivityCompat.html#finishAffinity%28android.app.Activity%29

@PhilippS 2014-12-08 20:47:38

Realy userful and easy solution if you are alread on API 16. Worked for me!

@Ryan 2015-08-28 23:09:33

reminder: this will only work for activities in that share the same taskAffinity name

@arsent 2016-10-05 19:51:42

this only work if you have just one activity in the history.

@Arun Sharma 2015-06-10 06:15:25

Add NO History Flag in the intent.

In activity B, start the activity C as below >>>>>>

Intent intent = new Intent(this, C.class);
intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY); 
startActivity(intent);
finish();

@GeetT 2015-05-17 03:09:02

For future research, try this code.

Intent intent = new Intent(context, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();

@Janne Oksanen 2015-08-20 13:23:23

These flags finally worked for me. What I did was I started the same Activity I was in with these flags and a boolean extra EXIT=true. The in onCreate() I checked the launch parameters for EXIT and called finish() if it was set true. That's a lot of hassle just to close your own app.

@Jake Basile 2011-04-26 18:10:07

Try adding FLAG_ACTIVITY_NEW_TASK as described in the docs for FLAG_ACTIVITY_CLEAR_TOP:

This launch mode can also be used to good effect in conjunction with FLAG_ACTIVITY_NEW_TASK: if used to start the root activity of a task, it will bring any currently running instance of that task to the foreground, and then clear it to its root state. This is especially useful, for example, when launching an activity from the notification manager.

So your code to launch A would be:

Intent intent = new Intent(this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(intent);
finish(); // call this to finish the current activity

@Martin 2011-04-26 18:30:44

Thanks but I've tried this. Still when I tap the back button after it shows C again. What can I be missing?

@Jake Basile 2011-04-26 18:35:36

How do you declare your activities in AndroidManifest.xml?

@Martin 2011-04-26 18:46:13

I've tried with android:launchMode="singleTop" but that didn't make any difference. I can't see what is wrong. So when you use this code and hit back button C will not show up?

@Jake Basile 2011-04-26 18:53:25

Are all the activities declared with the same taskAffinity?

@Jake Basile 2011-04-26 18:55:48

Huh, this doesn't work for me either. It should... I'll look into it.

@Jake Basile 2011-04-26 18:59:16

Try it with intent.addFlags(int), that made it work for me. I bet setFlags overrides the previous flags, so only NEW_TASK was getting added.

@Martin 2011-04-26 19:24:56

So irritating, I restarted the emulator and eclipse, cleaned the project and now it seems to be working just like you said. I mark this as the answer as this was the first one.

@Jake Basile 2011-04-26 19:42:47

Glad I could "help". Restarting Eclipse and the emulator tend to be near the top of my troubleshooting list.

@Surej 2011-10-10 11:19:34

@Jake Basile:Good one..Thanks..

@Kyle Clegg 2012-06-08 09:41:40

I have been frustrated with this for a couple hours now, with NOTHING seeming to work. I just realized that I am using Action Bar Sherlock SherlockActivities and not normal Android activities. Could this have something to do with it?

@dzeikei 2012-06-19 04:18:24

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_A‌​CTIVITY_NEW_TASK);

@Mike Repass 2012-09-17 23:17:30

@Kyle I struggled with this as well, take a look at: stackoverflow.com/a/12468288/614880

@2cupsOfTech 2014-07-23 17:08:37

doesn't work for me however calling finish() on source activity does what I needed to achieve

@Arno 2014-10-06 12:32:24

I had the same problem that this was not working. What fixed it for me was to call finish() after starting the new activity

@Hong 2014-11-18 02:41:16

@Arno Thank you! finish() did it. I would never have thought of it without your tip.

@Kevin D. 2015-01-29 02:49:28

Use addFlags not setFlags, figured it out the hard way. Also added Intent.FLAG_ACTIVITY_NEW_TASK

@Sam 2016-04-27 12:49:32

I also added one more clear Intent intent = new Intent(SingUpActivity.this, LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish();

@Rakesh Yadav 2016-12-21 03:46:39

@Sam thanks man. your comment helped.

@Pedro Okawa 2018-01-17 18:49:39

That's a good answer, but it may be replaced by without calling finish on current activity: Intent intent = new Intent(this, A.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent);

@steven smith 2018-10-14 04:42:27

Also, for APK21+ there is finishAndRemoveTask.

@Swap-IOS-Android 2014-10-31 12:08:53

i called activity_name.this.finish() after starting new intent and it worked for me.

I tried "FLAG_ACTIVITY_CLEAR_TOP" and "FLAG_ACTIVITY_NEW_TASK"

But it won't work for me... I am not suggesting this solution for use but if setting flag won't work for you than you can try this..But still i recommend don't use it

@Geng Jiawen 2014-07-11 07:46:04

This bothers me for a long time .Finally I worked it out by doing this:

In fragment,use:

Intent intent = new Intent(view.getContext(), A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(intent);

In Activity,use(add one more intent flag Intent.FLAG_ACTIVITY_CLEAR_TASK compared to fragment):

Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

@yosafatade 2014-09-26 15:58:05

If you are using androidannotations, you have to add: Intent.FLAG_ACTIVITY_CLEAR_TASK

@PhilippS 2014-12-08 20:46:34

Activity solutioin worked fine for me. Although I think with API 16 the solution from Daniel Schuler is easier.

@Arià 2015-01-05 12:09:58

Activity solution also worked for me, thanks!

@Krunal Indrodiya 2015-07-14 07:15:53

Working fine thanks.

@Marty Miller 2016-09-13 02:25:39

Thank you yosafatade, that was what I was missing!

@Abhijeet 2013-09-26 14:30:12

logout.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); logout.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

@Sathesh 2013-01-28 09:05:13

The given code works correctly. I have tried in the Application Life Cycle sample.

I haven't got B and C in the back stack after starting activity A with flag, FLAG_ACTIVITY_CLEAR_TOP

@slav 2012-12-20 19:53:11

Intent intent = new Intent(this, A.class);
startActivity(intent);
finish();

Related Questions

Sponsored Content

42 Answered Questions

[SOLVED] Is there a unique Android device ID?

89 Answered Questions

[SOLVED] Close/hide the Android Soft Keyboard

25 Answered Questions

[SOLVED] What and where are the stack and heap?

48 Answered Questions

12 Answered Questions

[SOLVED] Proper use cases for Android UserManager.isUserAGoat()?

14 Answered Questions

[SOLVED] Removing an activity from the history stack

27 Answered Questions

14 Answered Questions

[SOLVED] Clear back stack using fragments

77 Answered Questions

9 Answered Questions

[SOLVED] Android: Clear Activity Stack

Sponsored Content