How to show a dialog box after pressing the back button

Viewed 44601

By clicking the back button, I want to display a dialog box consisting of TextViews and a button called exit. After clicking the exit button it should come out from my app

I did like this,

@Override       
public void onBackPressed() {       
    System.out.println("hiiii");
    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.dialog);

    Button exitButton = (Button) dialog.findViewById(R.id.exit);
    System.out.println("inside dialog_started");
    exitButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            MainActivity.this.finish();
            dialog.dismiss();
        }
    });
    return;
}

in log cat hiiiii and "inside dialog_started" is printed, but dialog box is not coming. How can i get that dialog box on back button click?

8 Answers

Sometime activity keep history and it doesnt exit after confirmation .. in my case best solution.

private int k = 0;


@Override
public boolean onKeyDown(int keyCode, KeyEvent e) {

    if (keyCode == KeyEvent.KEYCODE_BACK) {
        oNBackPressedExitApp();
        return true;
    }

    return super.onKeyDown(keyCode, e);
}

@Override
protected void onStart() {
    super.onStart();
    k = 0;
}


public void oNBackPressedExitApp(){
        k++;
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Exit Confirmation");
        alertDialog.setIcon(R.drawable.ic_launcher);
        alertDialog.setMessage("Do you really want to exit the App?");

    if(k == 1) {
        alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();
                Intent homeScreenIntent = new Intent(Intent.ACTION_MAIN);
                homeScreenIntent.addCategory(Intent.CATEGORY_HOME);
                homeScreenIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(homeScreenIntent);
                return;
            }
        });
        alertDialog.setButton2("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                return;
            }
        });
        alertDialog.show();
    }
}
Related