java - 如何以编程方式退出 Android 应用程序?

标签 java android eclipse android-activity

我相信这个问题已经被问过很多次了,因为我读了一些。我的客户希望我在他的应用程序中放置一个按钮,用户可以点击并退出。我已阅读 this发现调用 finish() 就可以了。但是,完成只是关闭当前正在运行的 Activity ,对吗?我有很多 Activity ,所以在这种情况下,我必须传递每个 Activity 的实例并完成它们或将每个 Activity 变成单例模式。

我还知道 Activity.moveTaskToBack(true) 可以让你进入主屏幕。好的,这不是关闭,而是在后台处理该过程。那么这样有效吗?

我应该使用哪种方法来完全关闭应用程序?上述任何方法或上述方法的任何其他方法/其他用法?

最佳答案

在 API 16 中发布的 finishAffinity 方法会关闭所有正在进行的 Activity 并关闭应用程序:

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 in to 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();

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

替代方案:

getActivity().finish();
System.exit(0);


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


Process.sendSignal(Process.myPid(), Process.SIGNAL_KILL);


Intent i = new Intent(context, LoginActivity.class);
i.putExtra(EXTRA_EXIT, true);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(i);

来源:How to quit android application programmatically


希望能帮助到你!祝你好运!

关于java - 如何以编程方式退出 Android 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17719634/

相关文章:

android - 在Eclipse中使用genymotion插件进行gradle

java - GWT 未知参数 : -nosuperDevMode

java - 如何检查一个对象是否存在于java中的LinkedList中?

android - Action 条夏洛克

Android:为运行 KitKat 的设备定义操作栏样式

java - 有没有更好的方法来了解 Activity 的生命周期状态,例如 isOnStop、isOnPause 等 API?

java - Eclipse不可逆Dynamic Web Module 4.0选择; Tomcat 9 不支持

java - 如何从 jdom 中删除空格或空行

java - GWT CellTable 输入验证

java - 文本文件到字符串矩阵java