360

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?

braX
  • 11,506
  • 5
  • 20
  • 33
Martin
  • 7,190
  • 9
  • 40
  • 48

39 Answers39

479

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);
CurrentActivity.this.finish(); // if the activity running has it's own context


// view.getContext().finish() for fragments etc.
Ev0lv3zz
  • 58
  • 8
jakebasile
  • 8,084
  • 3
  • 28
  • 34
  • 32
    Thanks but I've tried this. Still when I tap the back button after it shows C again. What can I be missing? – Martin Apr 26 '11 at 18:30
  • How do you declare your activities in AndroidManifest.xml? – jakebasile Apr 26 '11 at 18:35
  • 1
    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? – Martin Apr 26 '11 at 18:46
  • Are all the activities declared with the same taskAffinity? – jakebasile Apr 26 '11 at 18:53
  • 1
    Huh, this doesn't work for me either. It should... I'll look into it. – jakebasile Apr 26 '11 at 18:55
  • 1
    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. – jakebasile Apr 26 '11 at 18:59
  • 1
    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. – Martin Apr 26 '11 at 19:24
  • 1
    Glad I could "help". Restarting Eclipse and the emulator tend to be near the top of my troubleshooting list. – jakebasile Apr 26 '11 at 19:42
  • 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? – Kyle Clegg Jun 08 '12 at 09:41
  • 5
    `intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);` – dzeikei Jun 19 '12 at 04:18
  • 2
    @Kyle I struggled with this as well, take a look at: http://stackoverflow.com/a/12468288/614880 – Mike Repass Sep 17 '12 at 23:17
  • 8
    doesn't work for me however calling finish() on source activity does what I needed to achieve – 2cupsOfTech Jul 23 '14 at 17:08
  • 11
    I had the same problem that this was not working. What fixed it for me was to call finish() after starting the new activity – Arno van Lieshout Oct 06 '14 at 12:32
  • 2
    @Arno Thank you! finish() did it. I would never have thought of it without your tip. – Hong Nov 18 '14 at 02:41
  • 1
    Use `addFlags` not `setFlags`, figured it out the hard way. Also added `Intent.FLAG_ACTIVITY_NEW_TASK` – Kevin D. Jan 29 '15 at 02:49
  • 23
    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(); – Samir Apr 27 '16 at 12:49
  • 1
    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);` – Pedro Okawa Jan 17 '18 at 18:49
  • 1
    Also, for APK21+ there is finishAndRemoveTask. – steven smith Oct 14 '18 at 04:42
182
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
Philippe A
  • 1,252
  • 9
  • 22
diesel
  • 3,296
  • 1
  • 20
  • 17
82

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.

Bhunnu Baba
  • 1,742
  • 15
  • 22
  • 3
    Be very careful while using this - If you are using login with FB or any similar sort of functionality – Skynet Mar 02 '15 at 12:26
  • 3
    @Skynet Why? What are the problems associated with doing this? – Alfie Woodland Mar 12 '15 at 16:32
  • 13
    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! – Skynet Mar 13 '15 at 07:18
  • This does not let an activity addded to backstack....this is not correct solution. – Tarun Deep Attri Apr 19 '16 at 05:17
  • Exactly i am looking for – Masum Jun 26 '18 at 10:50
  • only this answer worked for me . because all of the sudden back button went to wrong activity . idk how . but this one . at least made me sure that no activity took place in stack – Exutic Aug 16 '20 at 09:53
65

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);
Geng Jiawen
  • 8,904
  • 3
  • 48
  • 37
35

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

Daniel Schuler
  • 3,130
  • 2
  • 30
  • 28
31
  1. Add android:launchMode="singleTop" to the activity element in your manifest for Activity A
  2. Then use intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) and intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) when starting Activity A

This means that when Activity A is launched, all tasks on top of it are cleared so that A is top. A new back stack is created with A at the root, and using singleTop ensures you only ever launch A once (since A is now on top due to ..._CLEAR_TOP).

Joseph Earl
  • 23,351
  • 11
  • 76
  • 89
  • 3
    Yes. this is what I'm using now but that doesn't do it. Still C shows up when I hit the back button. – Martin Apr 26 '11 at 18:47
  • Odd, I used that in a project and it works fine... pressing back takes me to the home screen. Perhaps there's something else going on. Could you post your manifest? – Joseph Earl Apr 26 '11 at 18:48
  • I restarted the emulator and now it seems to be working just like you said. Thanks a lot for your help! – Martin Apr 26 '11 at 19:23
  • singleTop should have nothing to do with clearing the stack. – stdout Jul 26 '16 at 12:27
19

Try using

intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

and not

intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
cagdasalagoz
  • 460
  • 1
  • 12
  • 22
Muhammad Aamir Ali
  • 20,419
  • 10
  • 66
  • 57
  • This works. My assumption was that using `setFlags` would replace all default set flags but this was not the case – William Jul 07 '20 at 14:42
18

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

Jaydeep purohit
  • 1,536
  • 17
  • 20
10
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.
Firzan Shaikh
  • 515
  • 1
  • 6
  • 12
9

As per Wakka in Removing an activity from the history stack...


Add android:noHistory="true" attribute to your <activity> in the AndroidManifest.xml like this:

    <activity android:name=".MyActivity"
        android:noHistory="true">
    </activity>
Community
  • 1
  • 1
Richard Le Mesurier
  • 29,432
  • 22
  • 140
  • 255
9

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();
Biswajit_86
  • 3,661
  • 2
  • 22
  • 36
GeetT
  • 315
  • 3
  • 10
  • 1
    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. – Janne Oksanen Aug 20 '15 at 13:23
9

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

baswaraj
  • 629
  • 7
  • 7
  • only this answer works for me. Intent.FLAG_ACTIVITY_CLEAR_TOP and Intent.FLAG_ACTIVITY_NEW_TASK are not required – chrizonline Feb 03 '17 at 15:30
8

Use this code for starting a new Activity and close or destroy all other activity stack or back stack.

Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
Manaus
  • 407
  • 5
  • 9
Pankaj Talaviya
  • 3,328
  • 28
  • 31
7

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.

Adeel
  • 2,901
  • 7
  • 24
  • 34
Sujith Royal
  • 762
  • 10
  • 9
6

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)
Exigente05
  • 2,161
  • 3
  • 22
  • 42
5

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 = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK

If use this more than once, 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
4

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.

cagdasalagoz
  • 460
  • 1
  • 12
  • 22
Maximus
  • 8,351
  • 3
  • 29
  • 37
  • 7
    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. – Guillaume Brunerie Apr 26 '11 at 18:10
  • 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. – jakebasile Apr 26 '11 at 18:15
  • Duly noted. These are flags I need to learn about apparently. – Maximus Apr 26 '11 at 18:16
4

I found the answers here a little misleading because the code in the original question seems to work fine for me?

With A being the root activity, starting it from B or C only with FLAG_ACTIVITY_CLEAR_TOP does remove B and C from the back stack.

ianjoyner
  • 81
  • 1
3

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.

cagdasalagoz
  • 460
  • 1
  • 12
  • 22
Ashish Saini
  • 2,328
  • 25
  • 21
3

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();
cagdasalagoz
  • 460
  • 1
  • 12
  • 22
Tarun Deep Attri
  • 8,174
  • 8
  • 41
  • 56
3

Kotlin example:

      val intent = Intent(this@LoginActivity, MainActivity::class.java)
      intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
      startActivity(intent)
      finish()
stevyhacker
  • 1,847
  • 2
  • 23
  • 31
2

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

Abhijeet
  • 392
  • 2
  • 13
2
 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Mujeeb Rahaman T
  • 448
  • 3
  • 13
2

for me adding Intent.FLAG_ACTIVITY_CLEAR_TASK solved the problem

Intent i = new Intent(SettingsActivity.this, StartPage.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP  | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
finish();
Mohamed Mo'nes
  • 420
  • 3
  • 14
1

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);

cagdasalagoz
  • 460
  • 1
  • 12
  • 22
Vipin Yadav
  • 707
  • 5
  • 6
1

you wont get any activity pressing back button after that :

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | 
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finishAffinity();
finish();
Arnaud
  • 408
  • 4
  • 11
0

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

Sathesh
  • 6,323
  • 6
  • 36
  • 48
0

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

Swap-IOS-Android
  • 4,363
  • 6
  • 49
  • 77
0

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();
Arun Sharma
  • 179
  • 1
  • 5
0

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;
}
cagdasalagoz
  • 460
  • 1
  • 12
  • 22
Renjith JR
  • 189
  • 1
  • 3
  • 14
0

In manifest

android:launchMode="singleTask"

and

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
blackjack
  • 91
  • 1
  • 4
0

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
  • 3,328
  • 28
  • 31
0

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();
}
PhilipS
  • 379
  • 5
  • 15
0

This is how I solved the problem:

private boolean clearHistoryBackStack = true;

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

    if(clearHistoryBackStack)
        finishAffinity();
}
5chw4hn
  • 341
  • 3
  • 5
0

This code work for me in kotlin:

 val intent = Intent(this, MainActivity::class.java)
 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
 startActivity(intent)
 finish()
Shohan Ahmed Sijan
  • 4,391
  • 1
  • 33
  • 39
0

In addition to FLAG_ACTIVITY_CLEAR_TOP, you may try adding Intent.FLAG_ACTIVITY_SINGLE_TOP as well:

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

james
  • 26,141
  • 19
  • 95
  • 113
0

Though this may be coming late. I ran into this same problem while trying to move from activity A -> B -> C -> D, then to B if D returns true, I wanted to clear activity D and C.

val intent = Intent(this, ActivityUpload::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(intent)

I got the solution as described in the documentation.

For example, consider a task consisting of the activities: A, B, C, D. If D calls startActivity() with an Intent that resolves to the component of activity B, then C and D will be finished and B receive the given Intent, resulting in the stack now being: A, B.

Onwuka Daniel
  • 105
  • 1
  • 7
-2

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();
    }
}
-27
Intent intent = new Intent(this, A.class);
startActivity(intent);
finish();
slav
  • 312
  • 1
  • 2
  • 9