Android 创建新的Activity,禁止返回到前一个(或pre的pre)Activity (FLAG_ACTIVITY_CLEAR_TASK的应用)

来源:互联网 发布:关于网络管理的书 编辑:程序博客网 时间:2024/05/22 10:23

应用场景:在APP登录界面(A)中打开注册界面(B),在注册界面(B)提交用户名、密码等信息提交后,直接进入主界面(C)。此时如果用户按下了Back键,是不期望回到注册界面(B)或者是登录界面(A)的。

简单来说就是:activity A->B A启动B,此时栈中是A、B
B启动C,期望得到的栈是 C
此时用到了Intent.FLAG_ACTIVITY_CLEAR_TASK
Android API 中对FLAG_ACTIVITY_CLEAR_TASK 的解释:

public static final int FLAG_ACTIVITY_CLEAR_TASK
Added in API level 11
If set in an Intent passed to Context.startActivity(), this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty task, and any old activities are finished. This can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK.

这段就是说,设置了该flag(FLAG_ACTIVITY_CLEAR_TASK)会在新的activity启动之前,释放掉当前栈中的所有activity,因此新activity就成为了空工作栈中唯一的activity。当然,要和FLAG_ACTIVITY_NEW_TASK结合使用才有效(不过不加也可以)。
使用方法:在B中启动C

    Intent intent=new Intent();    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);    intent.setClass(B.this,C.class);    startActivity(intent);

参考
http://stackoverflow.com/questions/3473168/clear-the-entire-history-stack-and-start-a-new-activity-on-android
老外的解释总是那么简单粗暴有效,THKS。

最近又发现了一种用法
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
也能将栈中的activity上面的activity弹出。
API中对Intent.FLAG_ACTIVITY_CLEAR_TOP的解释
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.

0 0