首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >什么时候使用System.exit(0)和System.exit(2)?

什么时候使用System.exit(0)和System.exit(2)?
EN

Stack Overflow用户
提问于 2018-05-09 07:20:39
回答 3查看 3.1K关注 0票数 2

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

代码语言:javascript
复制
 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)代码如下

代码语言:javascript
复制
  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)之间的区别是什么。什么时候该特别使用它们?

EN

回答 3

Stack Overflow用户

发布于 2018-05-09 07:34:49

简短的回答:从不

在Android中,您不应该使用System.exit(0)System.exit(1),也不应该使用exit值,原因是它破坏了活动的生命周期。Android自己来处理这个问题,而试图与它打交道是一个非常糟糕的主意。

如果你真的想杀死你的应用程序,请使用Activity.finish()

您应该看看Android活动生命周期来真正理解它是如何工作的。

票数 4
EN

Stack Overflow用户

发布于 2018-05-09 07:27:29

exit(0)通常用于表示成功的终止。exit(2)或任何其他非零值通常表示终止不成功.

有关详细信息,请参阅此文档以获得更多信息。

票数 3
EN

Stack Overflow用户

发布于 2018-05-09 07:38:53

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

代码语言:javascript
复制
/**
         * 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);
        }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50247636

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档