1. 程式人生 > >Android 建立新的Activity,禁止返回到前一個(或pre的pre)Activity (FLAG_ACTIVITY_CLEAR_TASK的應用)

Android 建立新的Activity,禁止返回到前一個(或pre的pre)Activity (FLAG_ACTIVITY_CLEAR_TASK的應用)

應用場景:在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);

最近又發現了一種用法
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.