Android double click the return key to exit the program

  • 2020-06-07 05:15:08
  • OfStack

This article describes the Android double-click back key exit program implementation method, Android program development is a very practical function, to share with you for your reference. The specific methods are as follows:

1. Implementation idea:

When the user presses the back key, a timer is set to monitor whether the exit is achieved within 2 seconds. If the user does not press the back key again, the effect of the first press of the back key is cleared and the program is restored to the state before the first press of the back key. The timer is created each time the user presses the back key.

2. Function code:


/**
 *  Menu, return key response 
 */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
 // TODO Auto-generated method stub
 if(keyCode == KeyEvent.KEYCODE_BACK)
{ 
  exitBy2Click(); // Call double-click exit function 
}
 return false;
}
/**
 *  Double click to exit the function 
 */
private static Boolean isExit = false;

private void exitBy2Click() {
 Timer tExit = null;
 if (isExit == false) {
 isExit = true; //  Ready to quit 
 Toast.makeText(this, " then 1 Secondary exit procedure ", Toast.LENGTH_SHORT).show();
 tExit = new Timer();
 tExit.schedule(new TimerTask() {
  @Override
  public void run() {
  isExit = false; //  Cancel out 
  }
 }, 2000); //  if 2 If the back key is not pressed within seconds, the timer is started to cancel the task that has just been executed 

 } else {
 finish();
 System.exit(0);
 }
}

The onKeyDown() function in the above code can be found on the menu bar Source- > Override/Implement Methods find, double click to automatically add to the code.

I hope this article has been helpful for your Android programming.


Related articles: