在開發一個android應用軟體時,考慮如何關閉應用程式的問題。一開始採用當前Activity調用finish()來完成,但這種做法是不對的。 這幾天通過閱讀Android的frameworks層代碼時,發現平台提供了關閉程式的方法。 在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) { } }
ok,我們只需要取得ActivityManager的執行個體,並調用該方法即可正常關閉應用。 以下是關閉程式的程式碼片段:
private void exit2() {
ActivityManager actMgr = (ActivityManager) this .getSystemService(ACTIVITY_SERVICE);
actMgr.restartPackage(getPackageName()); }
調用上述方法就能徹底地關閉掉程式,一般僅僅調用finish()是無法徹底關閉程式的。 但要注意一點,調用系統服務需要在AndroidManifest.xml檔案中增加許可權。