Leaving android app with back button

android, android-lifecycle, back

Solution

You can try something like this (shows a dialog to confirm exit):

        @Override
        public void onBackPressed() {
                    new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
                            .setMessage("Are you sure you want to exit?")
                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                    System.exit(0);
                                }
                            }).setNegativeButton("No", null).show();
                }

It must be noted as it is mentioned in the comments below that exiting an app with System.exit is not recommended. A more "correct" way would probably be to broadcast an intent on back pressed and if the activities of your application received that intent finish themselves.

Problem

I want the users of my android app to leave my app when they press back at a certain activity. Can this be done?

Original source

Related problems