Android Back Button Exit Dialogue in Java

Here is how to show an Exit Alert Dialogue in android java when user presses back button

Exiting your app when a user pressing the back button without user permission may be a bad practice, it can cause the user to lose something like an important task, file, information etc.

In my opinion it is a good practice to ask the user if he wants to exit the app or not. we will learn that functionality for your app in the code below.

Ok, we have 2 ideas here to let a user know that the app may exit

first is asking the user to press the back key again, like pressing 2 times to exit the app

second option is

Showing a dialogue window (Alert Dialogue) to exit the app, we will learn both function’s java codes in this tutorial

Java code for asking user to press back button again to exit

@Override public void onBackPressed(){     backpress = (backpress + 1);     Toast.makeText(getApplicationContext(), " Press Back again to Exit ", Toast.LENGTH_SHORT).show();     if (backpress>1) {         this.finish();     } }

Alert Dialogue to ask user to exit app when back button pressed

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
            .setTitle("Really Exit?")
            .setMessage("Are you sure you want to exit?")
            .setNegativeButton(android.R.string.no, null)
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MainActivity.super.onBackPressed();
                    //this mainactivity must be replaced with your activity
                }

            }).create().show();
}}

, ,

Post navigation

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.