Android tutorial – Implement press BACK again to exit

Often users are spamming the back button in your app to go back to the main screen. This means they can exit your app by accident, and you don’t want that. In order to prevent this, we are going to override the onBackPressed() method so the user will exit the app only on double tapping the back button.

    boolean doubleBackToExitPressedOnce = false;
    public void onBackPressed() {
        if (doubleBackToExitPressedOnce) {

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

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

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

We are using postDelayed(runnable, time) because we want the boolean variable to reset itself if the user didn’t double tap.

Github repo with the full code can be found here

Leave a Reply

You must be logged in to post a comment.