Android – Request User Decision when Back Button is Pressed

Did you want to display a Dialog to the user asking him “Do you really want to quit?” when he presses the back button thus ending your current Activity? Here’s how to do it.

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;

public class TestMain extends Activity {

    private static final int DIALOG_REALLY_EXIT_ID = 0;

    // Called when the Activity is first created.
    public void onCreate(Bundle savedInstanceState) {

        // ...
    // other methods ...

    // creates Dialogs for this Activity
    protected Dialog onCreateDialog(int id) {
        final Dialog dialog;
        switch(id) {
            dialog = new AlertDialog.Builder(this).setMessage(
                                "Are you sure you want to exit?")
                    new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
            dialog = null;
        return dialog;

    // manages key presses not handled in other Views from this Activity
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK)

        return true;
        // use this instead if you want to preserve onKeyDown() behavior
        // return super.onKeyDown(keyCode, event);

We must figure out when the back button (identified by KeyEvent.KEYCODE_BACK) was pressed, and for that we use onKeyDown() method. From there we request the display of the Dialog by calling showDialog(). The AlertDialog interacting with the user is managed in the onCreateDialog() method.
Remember that the return value for onKeyDown() method matters:

  • If it is set by us to true or false (see the official documentation for more details on that) we are overriding the back button press behavior, thus the default Android behavior (implicit call of onBackPressed() method and there finish() on the Activity class) doesn’t occur. The Dialog appears and lets us decide if the Activity ends or not.
  • If we return super.onKeyDown(keyCode, event) we are just adding the behavior we want and this will be executed before the default one (we could use this to save important things before exit). In this case our Dialog would appear for just a brief moment and then the Activity would finish no matter what we do.


  1. Thanks, this helped me.

  2. it works like a charm

  3. Cool! thanks!

  4. This was what I need!

  5. Thank you very much for sharing this piece of code, that saved me a lot of time :)

Leave a Reply

You must be logged in to post a comment.