Leaving android app with back button

Sandah Aung picture Sandah Aung · Jul 25, 2013 · Viewed 18.3k times · Source

I want the users of my android app to leave my app when they press back at a certain activity. Can this be done?

Answer

An-droid picture An-droid · Jul 25, 2013

A good way is to wait for a second back

private boolean             _doubleBackToExitPressedOnce    = false;

@Override
public void onBackPressed() {

    Log.i(TAG, "onBackPressed--");
    if (_doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }
    this._doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Press again to quit", Toast.LENGTH_SHORT).show();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {

            _doubleBackToExitPressedOnce = false;
        }
    }, 2000);
}