退出Android应用程序

jopen 9年前

1. finish()方法

该方法可以结束当前 Activity,但是如果你的 App 有很多 Activity 的话,使用该方法显得有点捉襟见肘了。
另外,还有一个方法 finishActivity (int requestCode) ,关于这个方法,先看看 sdk 的 api 说明吧!

public void finishActivity (int requestCode)
Since: API Level 1

Force finish another activity that you had previously started with startActivityForResult(Intent, int).

Parameters requestCode

The request code of the activity that you had given to startActivityForResult(). 
If there are multiple activities started with this request code, they will all be finished.


也许你会这样理解 ,Activity1 通过方法 startActivityForResult (Intent, int) 启动 Activity2,
然后在 Activity2 中通过方法finishActivity (int requestCode)来结束 Activity1,但是很不幸运,不是这样的。不信你可以Demo一把! 

上面文档说得很明白,该方法强制关闭通过方法 startActivityForResult (Intent, int) 启动的 Activity,
也就是说在 Activity1 中的(重写)方法 onActivityResult(int requestCode, int resultCode, Intent data) 来接收 Activity2 返回的结果,
必须在 Activity1 中调用 finishActivity (int requestCode) 来结束 Activity2。
(一般在 onActivityResult  方法调用该方法结束 Activity2)。

Force finish another activity that you had previously started with startActivityForResult(Intent, int).

还有,下面两个方法,可以参阅文档以及源码研究一下。
finishActivityFromChild(Activity child, int requestCode)
finishFromChild(Activity child)

2. killProcess

通过调用 android.os.Process 的相关方法,结束 App,示例如下:
btn_exit.setOnClickListener(new Button.OnClickListener() {
    @Override
    public void onClick(View v) {
        android.os.Process.killProcess(android.os.Process.myPid());
    }
});

3. exit

我们知道,Java 的 exit(int code) 方法可以退出程序,通过查看该方法源码,知道它实际上是调用下面的方法:
Runtime.getRuntime().exit(code);

示例代码,如下所示:
btn_exit.setOnClickListener(new Button.OnClickListener() {
    @Override
    public void onClick(View v) {
    System.exit(0);//正常退出App
    }
});
接下来,我们研究一下这个方法。java.lang.System 这个类的该方法 jdk 说明:
exit
public static void exit(int status)

终止当前正在运行的 Java 虚拟机。参数用作状态码;根据惯例,非 0 的状态码表示异常终止。
该方法调用 Runtime 类中的 exit 方法。该方法永远不会正常返回。

调用 System.exit(n) 实际上等效于调用:

Runtime.getRuntime().exit(n)
 
参数:
status - 退出状态。
抛出:
SecurityException - 如果安全管理器存在并且其 checkExit 方法不允许以指定状态退出。
另请参见:
Runtime.exit(int)
也就是说,参数为非0值的话是异常退出程序。参数为0的话,就是正常退出。
看RunTime这个类的该方法源码:


public void exit(int status) {
        SecurityManager security = System.getSecurityManager();
if (security != null) {
   security.checkExit(status);
}
Shutdown.exit(status);
}


其api说明:
exit
public void exit(int status)


通过启动虚拟机的关闭序列,终止当前正在运行的 Java 虚拟机。此方法从不正常返回。可以将变量作为一个状态码;根据惯例,非零的状态码表示非正常终止。
虚拟机的关闭序列包含两个阶段。在第一个阶段中,会以某种未指定的顺序启动所有已注册的关闭钩子 (hook)(如果有的话),并且允许它们同时运行直至结束。
在第二个阶段中,如果已启用退出终结,则运行所有未调用的终结方法。一旦完成这个阶段,虚拟机就会暂停。
如果在虚拟机已开始其关闭序列后才调用此方法,那么若正在运行关闭钩子,则将无限期地阻断此方法。
如果已经运行完关闭钩子,并且已启用退出终结 (on-exit finalization),那么此方法将利用给定的状态码(如果状态码是非零值)暂停虚拟机;
否则将无限期地阻断虚拟机。

System.exit 方法是调用此方法的一种传统而便捷的方式。

参数:
status - 终止状态。按照惯例,非零的状态码表明非正常终止。
抛出:
SecurityException - 如果安全管理器存在,并且其 checkExit 方法不允许存在指定的状态

另请参见:
SecurityException, SecurityManager.checkExit(int), addShutdownHook(java.lang.Thread), 
removeShutdownHook(java.lang.Thread), runFinalizersOnExit(boolean), halt(int)

该方法又是调用 Shutdown 这个类的 exit() 方法。


static void exit(int status) {
boolean runMoreFinalizers = false;
synchronized (lock) {
   if (status != 0) runFinalizersOnExit = false;
   switch (state) {
   case RUNNING:/* Initiate shutdown */
       state = HOOKS;
       break;
   case HOOKS:/* Stall and halt */
       break;
   case FINALIZERS:
       if (status != 0) {
           /* Halt immediately on nonzero status */
           halt(status);
       } else {
           /* Compatibility with old behavior:
            * Run more finalizers and then halt
           */
           runMoreFinalizers = runFinalizersOnExit;
      }
     break;
   }
}
if (runMoreFinalizers) {
   runAllFinalizers();
   halt(status);
}
synchronized (Shutdown.class) {
   /* Synchronize on the class object, causing any other thread
             * that attempts to initiate shutdown to stall indefinitely
    */
   sequence();
   halt(status);
}
    }

其中,runAllFinalizers() 是一个本地方法:
JNIEXPORT void JNICALL
Java_java_lang_Shutdown_runAllFinalizers(JNIEnv *env, jclass ignored)
{
    jclass cl;
    jmethodID mid;

    if ((cl = (*env)->FindClass(env, "java/lang/ref/Finalizer"))
         && (mid = (*env)->GetStaticMethodID(env, cl,
             "runAllFinalizers", "()V"))) {
                 (*env)->CallStaticVoidMethod(env, cl, mid);
     }
}
System.exit() 的参数是把退出原因返回给系统, 一般来说可以是任何的整数 。

0 表示正常退出,1 表示非正常 。
最后说一下 finish() 与 exit 方法的区别:
finish()是Activity的类方法,仅仅针对Activity,当调用 finish() 时,只是将活动推向后台,并没有立即释放内存,活动的资源并没有被清理;当调用 System.exit(0) 时,退出当前 Activity 并释放资源(内存),但是该方法不可以结束整个 App 如有多个 Activty 或者有其他组件 service 等不会结束。
其实android的机制决定了用户无法完全退出应用,当你的 application 最长时间没有被用过的时候,android 自身会决定将 application 关闭了。

4. restartPackage 方法

ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);    
manager.restartPackage(getPackageName());

首先需要创建 ActivityManager 对象,然后调用 restartPackage() 方法(如果有兴趣的话,可以看源码)。
注意:getPackageName 获得当前应用包名称,如 mark.zhang
使用这种方式来退出 App,需要权限:


<uses-permission android:name="android.permission.RESTART_PACKAGES" />


加详细的说明,如下:
void android.app.ActivityManager.restartPackage(String packageName)

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 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 android.Manifest.permission.RESTART_PACKAGES to be able to call this method.

Parameters:
    packageName The name of the package to be stopped.

可以看出,相同的 UID 的进程会被kill,还会停止相关的服务以及移除所有的Activity,并且会发送一个广播。

注意一个问题:在 android2.2 之后,该方法不可以将应用程序结束,需要使用 ActivityManager 类的下面这个方法:
public void killBackgroundProcesses (String packageName)
api 文档说的很清楚:
public void restartPackage (String packageName)

Since: API Level 3
This method is deprecated.
This is now just a wrapper for killBackgroundProcesses(String); 
the previous behavior here is no longer available to applications 
because it allows them to break other applications by removing their alarms, stopping their services, etc.


另外,需要使用权限:


<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/> 


但是不管你怎么样折腾,还是无法退出App,呜呼哀哉!这里给出一个方法:
int currentVersion = android.os.Build.VERSION.SDK_INT;
if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
    Intent startMain = new Intent(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(startMain);
    System.exit(0);
} else {// android2.1
    ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    am.restartPackage(getPackageName());
}

关于 android.os.Build.VERSION.SDK_INT,可以参考
 http://blog.csdn.net/androidbluetooth/article/details/6778422

5. 小结

finish():结束当前 Activity,不会立即释放内存。遵循 android 内存管理机制。

exit():结束当前组件如 Activity,并立即释放当前 Activity 所占资源。

killProcess():结束当前组件如 Activity,并立即释放当前Activity  所占资源。

restartPackage():结束整个 App,包括 service 等其它 Activity 组件。

特别注意:
除了 finish() 方法可以调用 Activity 的生命周期方法如 onStop()、onDestroy(),其余三种退出 App 均不会调用 Activity 的生命周期方法。除非,在调用这几个方法之前或者之后主动调用 Activity 的生命周期方法。如:
System.exit(int);
onDestroy();

项目经历:
Actiivty A、B,A 启动 B,在 B 中点击 Back,然后回到 A,悲惨的一幕发生了,回到 A,A 居然也消失了......,并且没有调用 A 的 onDestroy 方法。
百思不得其解,冷静一下,既然点击 Back,那麽肯定会调用 B 的 onDestroy 方法,于是,看到杯具的来源:

    @Override
    protected void onDestroy() {
        super.onDestroy();
        android.os.Process.killProcess(android.os.Process.myPid());
    }


罪魁祸首是 android.os.Process.killProcess(android.os.Process.myPid()) 这句代码,它将 app 这个 process kill 掉,所以,看不到 A 再现,并且不会调用 A 的 onDestroy 方法。