Android press again to exit the app

In our actual development process, in order to prevent the user from accidentally pressing the return button to exit the application, we need to provide the user with an anti-accidental touch function, that is, let him press it again to exit, and it can be added on our main page. Many navigation pages can be added in their parent classes. The code is as follows:

//Declare a long type variable: used to store the moment when the "return key" was clicked last 
  private  long mExitTime;
     /**
     * Add return key listener
     * @param context
     */ 
  @Override 
    public  boolean  onKeyDown ( int keyCode, KeyEvent event)  {
         //Determine whether the user clicked the "return key" 
        if (keyCode == KeyEvent.KEYCODE_BACK) {
                 //The difference from the last time the return key was clicked 
            if (( System.currentTimeMillis() - mExitTime) > 2000 ) {
                     //If it is more than 2000ms, it is considered a misoperation, use Toast to prompt 
                Toast.makeText( this , "Press again to exit the program" , Toast.LENGTH_SHORT).show();
                 / /And record the moment when you click the "return button" this time, so that you can judge next time
                mExitTime = System.currentTimeMillis();
            } else {
                     //If less than 2000ms, it is considered that the user really wants to exit the program - call the System.exit() method to exit 
                System.exit( 0 );
            }
            return true;
     }
            return super.onKeyDown(keyCode, event);
    }

Leave a Comment

Your email address will not be published. Required fields are marked *