2025-04-30

Android的窗口類提供瞭歷史棧,我們可以通過stack的原理來巧妙的實現,這裡我們在D窗口打開A窗口時在Intent中直接加入標志Intent.FLAG_ACTIVITY_CLEAR_TOP,再次開啟A時將會清除該進程空間的所有Activity。
在D中使用下面的代碼:
Intent intent = new Intent();
intent.setClass(D.this, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //註意本行的FLAG設置
startActivity(intent);
finish();關掉自己
在A中加入代碼:
Override

protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub

super.onNewIntent(intent);

//退出

if ((Intent.FLAG_ACTIVITY_CLEAR_TOP & intent.getFlags()) != 0) {

finish();

}

}

A的Manifest.xml配置成android:launchMode=”singleTop”

原理總結:
一般A是程序的入口點,從D起一個A的activity,加入標識Intent.FLAG_ACTIVITY_CLEAR_TOP這個過程中會把棧中B,C,都清理掉。因為A是android:launchMode=”singleTop”
不會調用oncreate(),而是響應onNewIntent()這時候判斷Intent.FLAG_ACTIVITY_CLEAR_TOP,然後把A finish()掉。
棧中A,B,C,D全部被清理。所以整個程序退出瞭

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *