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

坚强是说给别人听的谎言 提交于 2019-11-27 15:49:21

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6298275/how-to-finish-every-activity-on-the-stack-except-the-first-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!