Skip to content Skip to sidebar Skip to footer

How To Prevent Accidental App Exit W/in Android Fragments/activities?

How Do I Prevent Accidental App Exit w/in Android? IE: When the he/she presses the back button and reaches the last activity in the BackStack, show a toast to ask if the user wants

Solution 1:

You can check when the back key is pressed in the main activity of your app. You can then show user an alertdialog for a confirmation to exit.

public boolean onKeyDown(int keyCode, KeyEvent event) {
    //Handle the back button
    if(keyCode == KeyEvent.KEYCODE_BACK) {          
        checkExit();             
        return true;
    }       
    else {
        return super.onKeyDown(keyCode, event);
    }

}

private void checkExit()
{
    AlertDialog.Builder builder = new AlertDialog.Builder(this);        
    builder.setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {

                   //take actions here accordingly as the user has pressed yes
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });      
    AlertDialog alert = builder.create();
    alert.show();       
}

Post a Comment for "How To Prevent Accidental App Exit W/in Android Fragments/activities?"