Display Alert on Back Button Pressed in Android Studio


When a user wants to exit from an application, he is prompted to exit from the application.

Alert means to get the user's input when needed. Most of us have played games and when we try to exit it by pressing the "Back" button in an Android phone, it will ask "Do you really want to exit?". So, this article explains how to prevent the user from exiting an application without giving a response.

Step 1

Create a new Project with the following parameters.


Step 2

Open your Main Activity file, in my case it is "BackPressActivity" and paste the following code into it.


package com.example.alertonbackpressdemo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class BackPressActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {

    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Do you want to Exit?");
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //if user pressed "yes", then he is allowed to exit from application
        builder.setNegativeButton("No",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //if user select "No", just cancel this dialog and continue with app
        AlertDialog alert=builder.create();

Let's understand the Alert Dialog and its various methods.

In code we use "builder.setCancelable(false);" so that user can't cancel this dialog by pressing back again or touch outside the alert dialog box and dismiss it. So the user must press one of the options you have provided.
Next is "builder.setMessage("Do you want to Exit?");". Here you can write your own message that will be displayed to the user in an alert.

"builder.setPositiveButton" will set a positive button in the left side. The parameter will accept the name of that button as you can see in code it is "Yes". The same thing is set for "builder.setNegativeButton". When you set these buttons, you need to pass a listener that will be fired when the user clicks one of the buttons.

Step 3

Run your application.




In this article, we learned "How to show Alert Dialog" and "Show dialog at BACK button pressed".