Android tutorial – Implement press BACK again to exit

This is how to implement the basic functionality that prevents accidentally exiting your app by tapping the back button

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;
    @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);
    }

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

Related Posts

Leave a reply