Android clear / finish previous activities except one

别来无恙 提交于 2019-12-10 16:18:24

问题


In android I have the following path:

Activity 1 -> Activity 2 -> Activity 3 -> ... Activity N -> press button ...

When the button is pressed I want to Clear/Finish ALL activities from Activity 2 until N and then go to Acitivy X. In other words I want to finish all activities down to the initial One and then move to another.

If I use the flags:

CLEAR_TOP, CLEAR_TASK, NEW_TASK etc

theoritically it would finish ALL previous activities with the initial one. Is there any way to keep the initial one alive and move to activity X?


回答1:


I'm not sure I understand the question. Or rather, the reason for not being able to use FLAG_ACTIVITY_CLEAR_TOP.

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

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.

If I understand correctly, that's exactly what you want. In particular for,

Activity 1 -> Activity 2 -> Activity 3 -> ... Activity N -> press button ...

Launching an Intent with Activity2.class and flags FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP would go back to the existing instance of Activity2 (instead of creating a new one) and deliver the new intent in onNewIntent(). You just need to add an extra to this intent, so that this method will know that it's supposed to call ActivityX afterwards.

That is, unless I'm missing something. :)




回答2:


if you have already visited a actitvity and have not called finish() on leaving it then do this

finish();
Intent mIntent = new Intent(Create_Your_Pizza.this, MainActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);;

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


来源:https://stackoverflow.com/questions/24026051/android-clear-finish-previous-activities-except-one

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