Android - 清除导航后退堆栈

Android - Clearing Navigation Backstack

我有 4 页。

来自 page_1 > page_2 > page_3 > page_4.

一旦用户到达 page_3 并单击按钮,它就会导航到 page_4。单击按钮后,我想清除所有导航历史记录,以便当用户返回 page_4 时,应用程序退出而不是返回 page_3。

我试过:

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

但是没有任何反应。我仍然可以返回到 page_3、page_2 等。我该如何做到这一点,以便当用户单击 page_3 上的按钮时,他会转到 page_4 并从page_4应该没有导航历史吧?

所有其他活动,例如 page_3、page_2、page_1、

使用FLAG_ACTIVITY_NO_HISTORY(如果设置,新的activity不会保存在历史堆栈中。):

intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

我不确定这些方法是否适合您。第一种方法是在从 page_3 转到 page_4 时添加 FLAG_ACTIVITY_TASK_ON_HOME:

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

因此,一旦您在 page_4 内按 BACK 按钮,它会先将您引导至主页 activity (MainActivity),然后您可以再次按 BACK 按钮退出应用 activity.

来自文档:

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.

第二种方式是在manifest的activity里面设置android:noHistory="true"。将此属性应用于 page_1 直到 page_4。但是这种方法有两个缺点。首先,您的 activity 完全没有返回堆栈。其次,一旦您按下主页按钮或接到来电,您使用此属性设置的活动就会被销毁。一直没找到这个题目,求CMIIW

尝试设置 Intent.FLAG_ACTIVITY_NO_HISTORY 和 Intent.FLAG_ACTIVITY_TASK_ON_HOME

来自文档 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.