標籤:android style blog http color io os ar for
工作過程式中遇到一個需要完全關閉應用程式的問題,每篇都是用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的應用程式的完全關閉方法:
1 /** 2 * Have the system perform a force stop of everything associated with 3 * the given application package. All processes that share its uid 4 * will be killed, all services it has running stopped, all activities 5 * removed, etc. In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED} 6 * broadcast will be sent, so that any of its registered alarms can * be stopped, notifications removed, etc. 7 * 8 * You must hold the permission * {@link android.Manifest.permission#RESTART_PACKAGES} to be able to 9 * call this method. 10 * 11 * @param packageName The name of the package to be stopped. 12 */13 public void restartPackage(String packageName) { 14 try { 15 ActivityManagerNative.getDefault().restartPackage(packageName); 16 } 17 catch (RemoteException e) { }18 }
所以如果要關閉整個應用程式的話只需要運行以下兩行代碼就行:
1 ActivityManager activityMgr= (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);2 activityMgr.restartPackage(getPackageName());
現在我們已經成功到一半了,那麼還有一半是什麼那,那就是我們老愛忘記的許可權,下面看看許可權代碼:
1 <uses-permission android:name="android.permission.RESTART_PACKAGES" />
參考原文:http://blog.163.com/yiba_suanzao/blog/static/130557377201131813952391/
【Android筆記】Android完全關閉應用程式