Android退出當前應用程序的方法
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
一般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全部被清理。所以整個程序退出了
在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全部被清理。所以整個程序退出了
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!