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

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

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


当前回答

要退出应用程序,您可以使用以下命令:

getActivity().finish();
Process.killProcess(Process.myPid());
System.exit(1);

也可以调用下面的方法来停止服务:

private void stopServices() {        
    final ActivityManager activityManager = SystemServices.getActivityManager(context);
    final List<ActivityManager.RunningServiceInfo> runningServices = activityManager.getRunningServices(Integer.MAX_VALUE);
    final int pid = Process.myPid();
    for (ActivityManager.RunningServiceInfo serviceInfo : runningServices) {
        if (serviceInfo.pid == pid && !SenderService.class.getName().equals(serviceInfo.service.getClassName())) {
            try {
                final Intent intent = new Intent();
                intent.setComponent(serviceInfo.service);
                context.stopService(intent);
            } catch (SecurityException e) { 
                 // handle exception
            }
        }
    }
}

其他回答

我觉得你要找的是这个

activity.moveTaskToBack(Boolean nonRoot);

我们希望代码健壮而简单。 该解决方案适用于旧设备和新设备。

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        getActivity().finishAffinity();
    } else{
        getActivity().finish();
        System.exit( 0 );
    }

如果您确实需要关闭应用程序,请认真考虑一下:为什么不让操作系统自行决定何时何地释放资源呢?

否则,如果你非常确定,就用

finish();

作为对@dave appleton评论的回应:第一件事是阅读大问题/答案组合@gabriel的帖子:退出应用程序是不受欢迎的吗?

现在假设我们有了这个,这里的问题仍然有一个答案,如果你要做任何关于退出的事情,你需要的代码是finish()。显然你可以有不止一项活动等等,但这不是重点。让我们看一些用例

You want to let the user quit everything because of memory usage and "not running in the background? Doubtfull. Let the user stop certain activities in the background, but let the OS kill any unneeded recourses. You want a user to not go to the previous activity of your app? Well, either configure it so it doesn't, or you need an extra option. If most of the time the back=previous-activity works, wouldn't the user just press home if he/she wants to do something else? If you need some sort of reset, you can find out if/how/etc your application was quit, and if your activity gets focus again you can take action on that, showing a fresh screen instead of restarting where you were.

所以最后,当然,finish()不会杀死所有东西,但我认为它仍然是你需要的工具。如果有“杀死所有活动”的用例,我还没有找到。

我认为应用程序在某些情况下应该被杀死。例如,有一个应用程序需要登录后才能使用。登录活动有两个按钮,“登录”和“取消”。当你点击“取消”按钮时,它肯定意味着“终止应用程序”。没有人希望应用程序在后台运行。所以我同意在某些情况下需要关闭应用程序。

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

exitProcess(0)

请参见文档。

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