How to quit android application programmatically

前端 未结 30 2731
迷失自我
迷失自我 2020-11-22 03:06

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?

30条回答
  •  梦谈多话
    2020-11-22 03:36

    finishAffinity();

    System.exit(0);

    If you will use only finishAffinity(); without System.exit(0); your application will quit but the allocated memory will still be in use by your phone, so... if you want a clean and really quit of an app, use both of them.

    This is the simplest method and works anywhere, quit the app for real, you can have a lot of activity opened will still quitting all with no problem.

    example on a button click

    public void exitAppCLICK (View view) {
    
        finishAffinity();
        System.exit(0);
    
    }
    

    or if you want something nice, example with an alert dialog with 3 buttons YES NO and CANCEL

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

提交回复
热议问题