何时使用System.exit(0)和System.exit(2)?

时间:2018-05-09 07:20:40

标签: android

我想在崩溃后重启应用程序。我正在使用下面的代码来执行该任务。

 Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

是的,它重新启动应用程序,但在其他教程中我找到相同的代码重新启动应用程序,但 System.exit(2)代码低于

  Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000, mPendingIntent);
System.exit(2);

是的,在这两种情况下应用程序都重新启动但我想知道System.exit(0)和System.exit(2)之间的区别。什么时候特别使用它们?

3 个答案:

答案 0 :(得分:4)

简短回答:从不

您永远不应该使用System.exit(0)System.exit(1)的原因,也不应该使用Android中的退出值,因为它会破坏活动的生命周期。 Android自己处理它,并试图干扰它是一个非常糟糕的主意。

如果您确实要杀死自己的应用,请使用Activity.finish()

你应该看一下Android Activity Lifecycle,真正了解它是如何运作的。

答案 1 :(得分:1)

exit(0)通常用于表示成功终止。 exit(2)或任何其他非零值表示一般终止失败。

有关详细信息,请参阅此documentation以获取更多信息。

答案 2 :(得分:1)

请参阅下面的退出实施代码:

/**
         * Terminates the currently running Java Virtual Machine. The
         * argument serves as a status code; by convention, a nonzero status
         * code indicates abnormal termination.
         * <p>
         * This method calls the <code>exit</code> method in class
         * <code>Runtime</code>. This method never returns normally.
         * <p>
         * The call <code>System.exit(n)</code> is effectively equivalent to
         * the call:
         * <blockquote><pre>
         * Runtime.getRuntime().exit(n)
         * </pre></blockquote>
         *
         * @param      status   exit status.
         * @throws  SecurityException
         *        if a security manager exists and its <code>checkExit</code>
         *        method doesn't allow exit with the specified status.
         * @see        java.lang.Runtime#exit(int)
         */


    public static void exit(int status) {
            Runtime.getRuntime().exit(status);
        }
相关问题