How to show a dialog to confirm that the user wishes to exit an Android Activity?

AndroidAndroid ActivityAndroid DialogActivity Finish

Android Problem Overview


I've been trying to show a "Do you want to exit?" type of dialog when the user attempts to exit an Activity.

However I can't find the appropriate API hooks. Activity.onUserLeaveHint() initially looked promising, but I can't find a way to stop the Activity from finishing.

Android Solutions


Solution 1 - Android

In Android 2.0+ this would look like:

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

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

In earlier versions it would look like:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
	//Handle the back button
	if(keyCode == KeyEvent.KEYCODE_BACK) {
		//Ask the user if they want to quit
    	new AlertDialog.Builder(this)
		.setIcon(android.R.drawable.ic_dialog_alert)
		.setTitle(R.string.quit)
		.setMessage(R.string.really_quit)
		.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {

				//Stop the activity
				YourClass.this.finish();	
			}

		})
		.setNegativeButton(R.string.no, null)
		.show();
    	
		return true;
	}
	else {
		return super.onKeyDown(keyCode, event);
	}
	
}

Solution 2 - Android

@Override
public void onBackPressed() {
	new AlertDialog.Builder(this)
	       .setMessage("Are you sure you want to exit?")
	       .setCancelable(false)
	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	               ExampleActivity.super.onBackPressed();
	           }
	       })
	       .setNegativeButton("No", null)
	       .show();
}

Solution 3 - Android

Have modified @user919216 code .. and made it compatible with WebView

@Override
public void onBackPressed() {
	if (webview.canGoBack()) {
		webview.goBack();
		
	}
	else
	{
	 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) {
                finish();
           }
       })
       .setNegativeButton("No", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
           }
       });
AlertDialog alert = builder.create();
alert.show();
	}
	
}

Solution 4 - Android

I'd prefer to exit with double tap on the back button than with an exit Dialog.

In this solution, it show a toast when go back for the first time, warning that another back press will close the App. In this example less than 4 seconds.

private Toast toast;
private long lastBackPressTime = 0;

@Override
public void onBackPressed() {
  if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
    toast = Toast.makeText(this, "Press back again to close this app", 4000);
    toast.show();
    this.lastBackPressTime = System.currentTimeMillis();
  } else {
    if (toast != null) {
    toast.cancel();
  }
  super.onBackPressed();
 }
}

Token from: http://www.androiduipatterns.com/2011/03/back-button-behavior.html

Solution 5 - Android

If you are not sure if the call to "back" will exit the app, or will take the user to another activity, you can wrap the above answers in a check, isTaskRoot(). This can happen if your main activity can be added to the back stack multiple times, or if you are manipulating your back stack history.

if(isTaskRoot()) {
    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) {
                YourActivity.super.onBackPressed;
           }
       })
       .setNegativeButton("No", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
           }
       });
    AlertDialog alert = builder.create();
    alert.show();

} else {
    super.onBackPressed();
}

Solution 6 - Android

in China, most App will confirm the exit by "click twice":

boolean doubleBackToExitPressedOnce = false;

@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }

    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            doubleBackToExitPressedOnce=false;                       
        }
    }, 2000);
} 

Solution 7 - Android

Using Lambda:

    new AlertDialog.Builder(this).setMessage(getString(R.string.exit_msg))
        .setTitle(getString(R.string.info))
        .setPositiveButton(getString(R.string.yes), (arg0, arg1) -> {
            moveTaskToBack(true);
            finish();
        })
        .setNegativeButton(getString(R.string.no), (arg0, arg1) -> {
        })
        .show();

You also need to set level language to support java 8 in your gradle.build:

compileOptions {
       targetCompatibility 1.8
       sourceCompatibility 1.8
}

Solution 8 - Android

First remove super.onBackPressed(); from onbackPressed() method than and below code:

@Override
public void onBackPressed() {
    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) {
                    MyActivity.this.finish();
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    AlertDialog alert = builder.create();
    alert.show();

}

Solution 9 - Android

Just put this code in your first activity 

@Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
            drawerLayout.closeDrawer(GravityCompat.END);
        }
        else {
// if your using fragment then you can do this way
            int fragments = getSupportFragmentManager().getBackStackEntryCount();
            if (fragments == 1) {
new AlertDialog.Builder(this)
           .setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    finish();
               }
           })
           .setNegativeButton("No", null)
           .show();

                
            } else {
                if (getFragmentManager().getBackStackEntryCount() > 1) {
                    getFragmentManager().popBackStack();
                } else {

           super.onBackPressed();
                }
            }
        }
    }

Solution 10 - Android

I like a @GLee approach and using it with fragment like below.

@Override
public void onBackPressed() {
    if(isTaskRoot()) {
        new ExitDialogFragment().show(getSupportFragmentManager(), null);
    } else {
        super.onBackPressed();
    }
}

Dialog using Fragment:

public class ExitDialogFragment extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity())
            .setTitle(R.string.exit_question)
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    getActivity().finish();
                }
            })
            .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    getDialog().cancel();
                }
            })
            .create();
    }
}

Solution 11 - Android

Another alternative would be to show a Toast/Snackbar on the first back press asking to press back again to Exit, which is a lot less intrusive than showing an AlertDialog to confirm if user wants to exit the app.

You can use the DoubleBackPress Android Library to achieve this with a few lines of code. Example GIF showing similar behaviour.

To begin with, add the dependency to your application :

dependencies {
    implementation 'com.github.kaushikthedeveloper:double-back-press:0.0.1'
}

Next, in your Activity, implement the required behaviour.

// set the Toast to be shown on FirstBackPress (ToastDisplay - builtin template)
// can be replaced by custom action (new FirstBackPressAction{...})
FirstBackPressAction firstBackPressAction = new ToastDisplay().standard(this);

// set the Action on DoubleBackPress
DoubleBackPressAction doubleBackPressAction = new DoubleBackPressAction() {
    @Override
    public void actionCall() {
        // TODO : Exit the application
        finish();
        System.exit(0);
    }
};

// setup DoubleBackPress behaviour : close the current Activity
DoubleBackPress doubleBackPress = new DoubleBackPress()
        .withDoublePressDuration(3000)     // msec - wait for second back press
        .withFirstBackPressAction(firstBackPressAction)
        .withDoubleBackPressAction(doubleBackPressAction);

Finally, set this as the behaviour on back press.

@Override
public void onBackPressed() {
    doubleBackPress.onBackPressed();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeter AView Question on Stackoverflow
Solution 1 - AndroidjaxView Answer on Stackoverflow
Solution 2 - AndroidChanakya VadlaView Answer on Stackoverflow
Solution 3 - Androidsuraj jainView Answer on Stackoverflow
Solution 4 - AndroidToni GamezView Answer on Stackoverflow
Solution 5 - AndroidGLeeView Answer on Stackoverflow
Solution 6 - AndroidSiweiView Answer on Stackoverflow
Solution 7 - AndroidvasiljevskiView Answer on Stackoverflow
Solution 8 - AndroidAnjali-SystematixView Answer on Stackoverflow
Solution 9 - AndroidMohit HoodaView Answer on Stackoverflow
Solution 10 - AndroidmariooshView Answer on Stackoverflow
Solution 11 - AndroidKaushik NPView Answer on Stackoverflow