Android - Clearing Navigation Backstack

谁说胖子不能爱 提交于 2019-12-02 00:31:21

I'm not sure that these methods will works for you. The first method is by adding FLAG_ACTIVITY_TASK_ON_HOME when you go to page_4 from page_3:

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

So once you press BACK button within page_4, it directs you to HOME activity (MainActivity) first, then you can press BACK button again to exit the app from this activity.

From the docs:

If set in an Intent passed to Context.startActivity(), this flag will cause a newly launching task to be placed on top of the current home activity task (if there is one). That is, pressing back from the task will always return the user to home even if that was not the last activity they saw. This can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK.

The second way is, set android:noHistory="true" within the activity in manifest. Apply this attribute for page_1 till page_4. But this method has two disadvantages. First, your activity is completely has no back stack. The second, the activities you set with this attribute get destroyed once you press HOME button or when you get an incoming call. I never found this topic, so please CMIIW.

for all the other activities like page_3,page_2,page_1,

Use FLAG_ACTIVITY_NO_HISTORY(If set, the new activity is not kept in the history stack.) :

intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

Try set Intent.FLAG_ACTIVITY_NO_HISTORY And Intent.FLAG_ACTIVITY_TASK_ON_HOME

From documentation Intent.FLAG_ACTIVITY_NO_HISTORY

If set, the new activity is not kept in the history stack. As soon as the user navigates away from it, the activity is finished. This may also be set with the noHistory attribute.

Intent.FLAG_ACTIVITY_TASK_ON_HOME

If set in an Intent passed to Context.startActivity(), this flag will cause a newly launching task to be placed on top of the current home activity task (if there is one). That is, pressing back from the task will always return the user to home even if that was not the last activity they saw. This can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK.

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