android初學之退出應用程序

有不少界面的應用下面的方法是行不通的:
 第一種方法:首先獲取當前進程的id,而後殺死該進程。
 android.os.Process.killProcess(android.os.Process.myPid())
 經過這種方式不能將應用程序徹底殺死,而且他不會把當前應用應用的Activity的task任務棧清空 android

 第二種方法:終止當前正在運行的Java虛擬機,致使程序終止
 System.exit(0);
 不會把本身的應用程序殺死 this

 第三種方法:強制關閉與該包有關聯的一切執行
 ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);   
 manager.restartPackage(getPackageName());
 <uses-permission android:name="android.permission.RESTART_PACKAGES" /> rest

 只能殺死別人,不能殺死本身
 
其餘方法:
1:打開系統主屏來模擬應用退出的效果,這和用戶按Home鍵沒有什麼區別。
 Intent intent = new Intent(Intent.ACTION_MAIN);
 intent.addCategory(Intent.CATEGORY_HOME);
 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 startActivity(intent); 
 
 當應用程序再次打開的時候,進入的仍是原來退出時顯示的界面:例如你在a.Activity界面調用了上面的方法,那麼在程序再次進入的時候仍是在a.Activity 進程

2,首先要說明該方法運行在Android 1.5 API Level爲3以上才能夠
 private void exit2() {
  ActivityManager actMgr = (ActivityManager) this .getSystemService(ACTIVITY_SERVICE);
  actMgr.restartPackage(getPackageName());
 }
 在清單文件中配置權限  android.Manifest.permission#RESTART_PACKAGES
 
 3. 根據Activity的聲明週期
 咱們在A窗口打開B窗口時在Intent中直接加入標誌Intent.FLAG_ACTIVITY_CLEAR_TOP,這樣開啓B時將會清除該進程空間的全部Activity。
 在A窗口中使用下面的代碼調用B窗口
 
 Intent intent = new Intent();
 intent.setClass(Android123.this, CWJ.class);
 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG設置
 startActivity(intent); get

相關文章
相關標籤/搜索