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

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

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


当前回答

简单和简单的方法退出应用程序

Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);

其他回答

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

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
            }
        }
    }
}
getActivity().finish();
System.exit(0);

这是退出应用程序的最佳方式!!

对我来说最好的解决方案。

从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();

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

只是在终止应用程序的残酷方法列表中添加一个:

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

如果你在Activity中,最好使用finish(),如果你在Fragment中,最好使用getActivity().finish()。

如果你想完全退出应用程序,那么使用:

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