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

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

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


当前回答

public void quit() {
        int pid = android.os.Process.myPid();
        android.os.Process.killProcess(pid);
        System.exit(0);
    }

其他回答

finishAffinity ();

System.exit(0);

如果你只使用finishAffinity();没有system . exit (0);你的应用程序将退出,但分配的内存仍然会被你的手机使用,所以…如果你想要一个干净的,真正退出的应用程序,使用他们两个。

这是最简单的方法,在任何地方都适用,退出应用程序,你可以有很多活动打开仍然会退出所有没有问题。

示例对一个按钮进行单击

public void exitAppCLICK (View view) {

    finishAffinity();
    System.exit(0);

}

或者如果你想要一些漂亮的东西,例如一个警报对话框,有3个按钮是,否和取消

// alertdialog for exit the app
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

// set the title of the Alert Dialog
alertDialogBuilder.setTitle("your title");

// set dialog message
alertDialogBuilder
        .setMessage("your message")
        .setCancelable(false)
        .setPositiveButton("YES"),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                                        int id) {
                        // what to do if YES is tapped
                        finishAffinity();
                        System.exit(0);
                    }
                })

        .setNeutralButton("CANCEL"),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                                        int id) {
                        // code to do on CANCEL tapped
                        dialog.cancel();
                    }
                })

        .setNegativeButton("NO"),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                                        int id) {
                        // code to do on NO tapped
                        dialog.cancel();
                    }
                });

AlertDialog alertDialog = alertDialogBuilder.create();

alertDialog.show();

这可能很晚了,而且根据指导方针,您不应该自己处理生命周期过程(因为操作系统为您做了)。一个建议是,你在你所有的活动中注册一个广播接收器,在他们的onReceive()中使用“finish()”&每当你希望退出时,你可以简单地传递一个意图,指示所有活动必须关闭..... 尽管要确保在onDestroy()方法中“取消注册”接收器。

只需要使用finish()返回键按onKeypressed()

这不是一个好的决定,因为它违背了Android的应用程序处理原则。Android不会终止任何进程,除非绝对不可避免。这有助于应用程序启动得更快,因为它们总是保存在内存中。因此,您需要一个非常特殊的理由来终止应用程序的进程。

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