如何以编程方式退出android应用程序 [英] How to quit android application programmatically

查看:38
本文介绍了如何以编程方式退出android应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  1. System.runFinalizersOnExit(true)
    (或)
  2. android.os.Process.killProcess(android.os.Process.myPid());

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

解决方案

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

this.finishAffinity();

<块引用>

完成此活动以及当前任务中紧邻其下方的所有具有相同关联的活动.这通常用于当应用程序可以启动到另一个任务(例如从它理解的内容类型的 ACTION_VIEW)并且用户已经使用向上导航从当前任务切换到它自己的任务时使用.在这种情况下,如果用户向下导航到第二个应用程序的任何其他活动,作为任务切换的一部分,所有这些活动都应该从原始任务中删除.

请注意,此完成不允许您将结果传递给前一个活动,如果您尝试这样做,则会引发异常.

由于 API 21,您可以使用非常相似的命令

finishAndRemoveTask();

<块引用>

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

I Found some codes for quit an Android application programatically. By calling any one of the following code in onDestroy() will it quit application entirely?

  1. System.runFinalizersOnExit(true)
    (OR)
  2. android.os.Process.killProcess(android.os.Process.myPid());

I dont want to run my application in background after clicking quit button. Pls suggest me can i use any one of these code to quit my app? If so which code can i use? Is it good way to quit the app in Android?

解决方案

Since API 16 you can use the finishAffinity method, which seems to be pretty close to closing all related activities by its name and Javadoc description:

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.

Since API 21 you can use a very similar command

finishAndRemoveTask();

Finishes all activities in this task and removes it from the recent tasks list.

这篇关于如何以编程方式退出android应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆