首页 > 代码库 > 【Android笔记】Android完全关闭应用程序

【Android笔记】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的应用程序的完全关闭方法:

 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完全关闭应用程序