Android 完全關閉應用程序
在工作過程序中遇到一個需要完全關閉應用程序的問題,在網絡上找了一大堆的文章,每篇都是用
System.exit(0) 或者 android.os.Process.killProcess(android.os.Process.myPid()) 這兩種方法,
但是我試過了, System.exit(0) 這個根本不行,而 android.os.Process.killProcess(android.os.Process.myPid()) 這個只能關閉當前的 Activity ,也就是對于一個只有單個 Activity 的應用程序有效,如果對于有多外 Activity 的應用程序它就無能為力了。
下面我介紹一下對于多個 Activity 的應用程序的完全關閉方法:
在 ActivityManager 類中提供了如下的方法:
/**
* Have the system perform a force stop of everything associated with
* the given application package. All processes that share its uid
* will be killed, all services it has running stopped, all activities
* removed, etc. In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
* broadcast will be sent, so that any of its registered alarms can * be stopped, notifications removed, etc.
*
* You must hold the permission * {@link android.Manifest.permission#RESTART_PACKAGES} to be able to
* call this method.
*
* @param packageName The name of the package to be stopped.
*/
public void restartPackage(String packageName) {
try {
ActivityManagerNative.getDefault().restartPackage(packageName);
}
catch (RemoteException e) { }
}
所以如果要關閉整個應用程序的話只需要運行以下兩行代碼就行:
ActivityManager activityMgr= (ActivityManager) this.getSystemService(ACTIVITY_SERVICE );
activityMgr.restartPackage(getPackageName());
最后還需要添加這個權限才行:
<!-- 關閉應用程序的權限 -->
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
多網友可能發現自己的Android程序有很多Activity,比如說主窗口A,調用了子窗口B,在B中如何關閉整個Android應用程序呢? 這里給大家三種比較簡單的方法實現。
首先要說明在B中直接使用finish(),接下來手機顯示的還是主窗口A,所以一起來看看是如何實現的吧.
1. Dalvik VM的本地方法
android.os.Process.killProcess(android.os.Process.myPid()) //獲取PID,目前獲取自己的也只有該API,否則從/proc中自己的枚舉其他進程吧,不過要說明的是,結束其他進程不一定有權限,不然就亂套了。
System.exit(0); //常規java、c#的標準退出法,返回值為0代表正常退出
2. 任務管理器方法
首先要說明該方法運行在Android 1.5 API Level為3以上才可以,同時需要權限android.permission.RESTART_PACKAGES,我們直接結束自己的package即可,直接使用ActivityManager類的restartPackage方法即可,參數為package name,該類通過getSystemService(Context.ACTIVITY_SERVICE)來實例化ActivityManager對象,這種方法系統提供的,但需要顯示聲明權限,所以使用中需要綜合考慮。
3. 根據Activity的聲明周期
我們知道Android的窗口類提供了歷史棧,我們可以通過stack的原理來巧妙的實現,這里我們在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);
接下來在B窗口中需要退出時直接使用finish方法即可全部退出。