SoFunction
Updated on 2025-03-11

How to exit the program by double-clicking the return key on Android

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

1. Implementation ideas:

When the user presses the return key, set a timer to monitor whether the exit has been achieved within 2 seconds. If the user does not press the return key, the effect of pressing the return key for the first time is cleared, so that the program can be restored to the state before the return key is first pressed. The timer is created every time the user presses the return 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 the double-click to 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; // Prepare to exit (this, "Press again to exit the program", Toast.LENGTH_SHORT).show();
 tExit = new Timer();
 (new TimerTask() {
  @Override
  public void run() {
  isExit = false; // Cancel and exit  }
 }, 2000); // If the return key is not pressed within 2 seconds, the startup timer will cancel the task you just executed
 } else {
 finish();
 (0);
 }
}

In the above codeThe onKeyDown() function can be found in the menu bar Source->Override/Implement Methods, and can be automatically added to the code by double-clicking.

I hope this article will be helpful to everyone's Android programming design.