Back Button Double Click Exit - (Android Essentials: XML & Java)

private boolean doubleBackToExitPressedOnce = false;

public void onBackPressed() {
    if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
        // There is a previous step, navigate back one step
    } else {
        // No previous step, show exit confirmation
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed(); // This will exit the app

        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "Press back again to exit", Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {
            public void run() {
                doubleBackToExitPressedOnce = false;
        }, 2000); // Reset the flag after 2 seconds

This handy code snippet enhances the user experience by preventing accidental exits from your Android app. Instead of closing the app with a single tap of the back button, users are required to press the back button twice within a short time frame to confirm their intent to exit. This feature is particularly useful for apps where accidental exits can be frustrating, such as games or productivity applications.

Here's how this code works:

  1. A boolean variable doubleBackToExitPressedOnce is used to track if the back button has been pressed once.

  2. When the back button is pressed, the onBackPressed() method is called.

  3. The code checks if there are entries in the fragment back stack:

    • If there are, it calls super.onBackPressed() to navigate back to the previous fragment.

    • If the stack is empty, it checks the doubleBackToExitPressedOnce flag.

  4. If the flag is false, it means this is the first back press, so the flag is set to true, and a Toast message is shown to instruct the user to press back again to exit.

  5. A Handler is then used to set the flag back to false after 2 seconds. If the user presses the back button again before the 2 seconds are up, the app will exit. If not, the flag is reset, and the app will not exit until the back button is pressed twice again.

To use this code in your app:

  1. Copy the private boolean doubleBackToExitPressedOnce = false; line and declare it in your Activity.

  2. Copy the overridden onBackPressed() method into the same Activity.

  3. Customize the Toast message as desired.

  4. Ensure you import the necessary classes such as Toast and Handler.

Now, the double back press to exit functionality should be set up. When the back button is pressed once, a toast message will appear, prompting the user to press again to exit. If the user does not press again within 2 seconds, the action will be cancelled.