0

I want to exit the app only when double tap continously. I am using fragment class. I used the below code but doesn't work

private long lastPressedTime;
private static final int PERIOD = 2000;

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
    switch (event.getAction()) {
    case KeyEvent.ACTION_DOWN:
        if (event.getDownTime() - lastPressedTime < PERIOD) {
            finish();
        } else {
            Toast.makeText(getApplicationContext(), "Press again to exit.",
                    Toast.LENGTH_SHORT).show();
            lastPressedTime = event.getEventTime();
        }
        return true;
    }
}
return false;
}

please guide me how to implement this in an app.

3 Answers3

0

Remove your implementation inside onKeydown and try this code

@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);
} 
williamj949
  • 11,166
  • 8
  • 37
  • 51
0
@Override
public void onBackPressed() {}

in your activity, because activity responsible for back button handling

Look to this question, it has not got an accepted answer, but contain some solutions

Community
  • 1
  • 1
Kirill Shalnov
  • 2,216
  • 1
  • 19
  • 21
0

try this :

    private boolean doubleBackToExitPressedOnce;

@Override
public void onBackPressed() {
    Log.i(tag, "Start: On Back Pressed!");

    if (doubleBackToExitPressedOnce) {
        Log.i(tag, "Double Back Pressed!");

        super.onBackPressed();
        return;
    }
    doubleBackToExitPressedOnce = true;
    Toast.makeText(this, R.string.msg_exit, Toast.LENGTH_SHORT).show();

    Timer t = new Timer();
    t.schedule(new TimerTask() {

        @Override
        public void run() {
            doubleBackToExitPressedOnce = false;
        }
    }, 2500);

}

dont forget to add this line in onResume:

@Override
protected void onResume() {
    doubleBackToExitPressedOnce = false;
}
Milad Faridnia
  • 9,113
  • 13
  • 65
  • 78