SoFunction
Updated on 2025-04-10

Android implements the return key to exit by clicking twice

When making Android applications, we often need to judge the user's operation on the return key. Generally, in order to prevent misoperation, we prompt the user to exit the application when the user presses the return key twice in a row.

The basic principle of the first implementation is that when the BACK key is pressed, it will be captured by onKeyDown. If it is determined that it is the BACK key, then the exit method will be executed.
In the exit method, the value of isExit will be judged first. If it is false, it will be set to true. At the same time, a prompt will be popped up, and a message will be sent after 2000 milliseconds (2 seconds), and the value will be restored to false in the Handler. If the BACK key is pressed again within 2 seconds of sending the message, the exit method is executed again. At this time, the value of isExit is true, the exit method will be executed.

package ;

import ;
import ;
import ;
import ;
import ;
import ;

public class MainActivity extends Activity {

  // Define a variable to identify whether to exit  private static boolean isExit = false;

  Handler mHandler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
      (msg);
      isExit = false;
    }
  };

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.activity_main);
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
      exit();
      return false;
    }
    return (keyCode, event);
  }

  private void exit() {
    if (!isExit) {
      isExit = true;
      (getApplicationContext(), "Press again to exit the program",
          Toast.LENGTH_SHORT).show();
      // Use handler to delay sending change status information      (0, 2000);
    } else {
      finish();
      (0);
    }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.