How to finish every activity on the stack except the first in Android
Asked Answered
P

2

23

I'm porting an iPhone app to Android and I can't seem to find a means to pop each activity on the stack except the root activity.

In objective-c I would do something like the below

[navController popToRootViewControllerAnimated:YES];

Anyone know if I can effectively call "finish()" on each activity after some action?

Pye answered 9/6, 2011 at 19:38 Comment(2)
I'm not 100% sure of what you're asking, but it's definitely safe to call finish() on an Activity once you're done with it. That will bring you back to whichever activity is before it in the stack.Babism
finish() will only pop back one level from the navigation stackSkewer
W
40

If you want to start one Activity, say, your homescreen, and remove every other Activity in your application's stack, you can use:

Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Removes other Activities from stack
startActivity(intent);

If you also want to provide this event in the MainActivity (such as a logo click in the title bar), you can add the FLAG_ACTIVITY_SINGLE_TOP flag as well to make sure it does not add another instance of itself to the stack.

Wertheimer answered 9/6, 2011 at 19:42 Comment(1)
it recreates first activity, I mean it calls onCreate() of MainActivityDownbeat
J
3

Look at http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP: you can startActivity on the root activity with this flag, and it will blow away all activities above it. You should read the docs carefully about the intent delivery behavior.

Jarvis answered 9/6, 2011 at 19:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.