[java] Clicking the back button twice to exit an activity

Recently, I needed to implement this back button feature in an app of mine. The answers on the original question were useful, but I had to take two more points into consideration:

  1. At some points in time, the back button is disabled
  2. The main activity is using fragments in combination with a back stack

Based on the answers and comments, I created the following code:

private static final long BACK_PRESS_DELAY = 1000;

private boolean mBackPressCancelled = false;
private long mBackPressTimestamp;
private Toast mBackPressToast;

@Override
public void onBackPressed() {
    // Do nothing if the back button is disabled.
    if (!mBackPressCancelled) {
        // Pop fragment if the back stack is not empty.
        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            super.onBackPressed();
        } else {
            if (mBackPressToast != null) {
                mBackPressToast.cancel();
            }

            long currentTimestamp = System.currentTimeMillis();

            if (currentTimestamp < mBackPressTimestamp + BACK_PRESS_DELAY) {
                super.onBackPressed();
            } else {
                mBackPressTimestamp = currentTimestamp;

                mBackPressToast = Toast.makeText(this, getString(R.string.warning_exit), Toast.LENGTH_SHORT);
                mBackPressToast.show();
            }
        }
    }
}

The code above assumes that the support library is used. If you use fragments but not the support library, you want to replace getSupportFragmentManager() by getFragmentManager().

Remove the first if, if the back button is never cancelled. Remove the second if, if you don`t use fragments or a fragment back stack

Also, it is important to be aware that the method onBackPressed is supported since Android 2.0. Check this page for an elaborate description. To make the back press feature work on older versions as well, add the following method to your activity:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
            && keyCode == KeyEvent.KEYCODE_BACK
            && event.getRepeatCount() == 0) {
        // Take care of calling this method on earlier versions of
        // the platform where it doesn't exist.
        onBackPressed();
    }

    return super.onKeyDown(keyCode, event);
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to back-button

Android: Quit application when press back button JavaScript or jQuery browser back button click detector Clicking the back button twice to exit an activity How to exit from the application and show the home screen? Android - How To Override the "Back" button so it doesn't Finish() my Activity? Preventing iframe caching in browser How to exit when back button is pressed?