john peter
john peter

Reputation: 11

My application immediately exits when i i press back button, dont wait for confirmation from user

when i press back button, application immediately exits and dont wait for confirmation from user "Are you sure ?"

Here is my onbackpressed code

@Override
public void onBackPressed() {
    super.onBackPressed();

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

            })
            .setNegativeButton("No", null)
            .show();

}

anyone here who can help me

Upvotes: 1

Views: 59

Answers (3)

Atul Gangwar
Atul Gangwar

Reputation: 1

To remove the app from background also u can use the below code.

@Override
public void onBackPressed() {

new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("Closing Application")
        .setMessage("Are you sure you want to close this application?")
        .setPositiveButton("Yes", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                super.onBackPressed();
                moveTaskToBack(true);                          
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(1);
            }

        })
        .setNegativeButton("No", null)
        .show();

}

Upvotes: 0

Rasoul Miri
Rasoul Miri

Reputation: 12232

remove this line

 super.onBackPressed();

Upvotes: 1

Lucifer
Lucifer

Reputation: 29670

You need to remove super.onBackPressed(); before the dialog appears

Try this way,

@Override
public void onBackPressed() {

    new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Closing Application")
            .setMessage("Are you sure you want to close this application?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    super.onBackPressed();
                }

            })
            .setNegativeButton("No", null)
            .show();

}

Upvotes: 1

Related Questions