我找到了一些以编程方式退出Android应用程序的代码。通过在onDestroy()中使用以下任何代码,它会完全退出应用程序吗?

System.runFinalizersOnExit(真正的) (或) android.os.Process.killProcess (android.os.Process.myPid ());

我不想在点击退出按钮后在后台运行我的应用程序。 请告知我是否可以使用这些代码中的任何一个来退出我的应用程序?如果可以,我可以使用哪个代码?在Android中退出应用程序是一个好方法吗?


当前回答

如果你正在使用Kotlin,退出应用程序的正确方法和System.exit()的替代方法是一个内置方法

exitProcess(0)

请参见文档。

数字0作为参数表示打算退出,并且没有发生错误。

其他回答

放弃一份申请是不受欢迎的吗?通过这个链接。它回答了你的问题。系统负责终止应用程序的工作。

假设你有两个活动A和B,你从A导航到B,当你点击返回按钮,你的活动B从背堆栈弹出并销毁。后堆栈活动A中的前一个活动集中。

您应该让系统决定何时终止应用程序。

公共无效处理()

当您的活动完成并应该关闭时调用它。

假设你有很多活动。你可以使用动作条。点击主页图标导航到应用程序的MainActivity。在MainActivity中单击返回按钮退出应用程序。

这将杀死任何东西;)

int p = android.os.Process.myPid();
android.os.Process.killProcess(p);

正确和准确的解决方案退出应用程序的按钮点击是使用下面的代码:

//On Button Back按下事件

public void onBackPressed()
{ 
   moveTaskToBack(true);
   finish();
}

android中没有退出应用程序, SampleActivity.this.finish ();将完成当前活动。

当你从一个活动切换到另一个活动时,要坚持完成前一个活动

Intent homeintent = new Intent(SampleActivity.this,SecondActivity.class);
startActivity(homeintent);
SampleActivity.this.finish();

从API 16开始,你可以使用finishAffinity方法,它似乎非常接近于通过它的名称和Javadoc描述关闭所有相关的活动:

this.finishAffinity();

Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and into its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch. Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.


从API 21开始,您可以使用非常类似的命令

finishAndRemoveTask();

完成此任务中的所有活动,并将其从最近任务列表中移除。