Implement application indispensable event, two clicks to achieve the return key to exit the application, here to write two methods are very simple, first began Method 1:
Define a time interval of two clicks back button
// first click and the second click time interval of private long exitTime;
Then click the back key to achieve events
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){ exit(); return true; } return super.onKeyDown(keyCode, event); } private void exit(){ if((System.currentTimeMillis() - exitTime) > 2000){ Toast.makeText(this, "再次点击退出应用", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); }else{ finish(); System.exit(0); } }
Next implementation 2, Handler delay by sending messages reach the exit status change application:
1 // definition of a variable is determined whether to exit 2 Private Boolean = isExit to false ; . 3 . 4 Handler Handler = new new Handler () { . 5 @Override . 6 public void the handleMessage (@NonNull the Message MSG) { . 7 super.handleMessage (MSG); . 8 isExit = to false ; . 9 } 10 };
Events then click on the system to achieve the return key (note method exit the judgment is "isExit!"):
1 @Override 2 public boolean onKeyDown(int keyCode, KeyEvent event) { 3 if(keyCode == KeyEvent.KEYCODE_BACK){ 4 exit(); 5 return false; 6 } 7 return super.onKeyDown(keyCode, event); 8 } 9 10 private void exit(){ 11 if(!isExit){ 12 isExit = true; 13 Toast.makeText ( the this , " Click again to exit the application " , Toast.LENGTH_SHORT) the .Show (); 14 // send status change message by the delay Handler 15 handler.sendEmptyMessageDelayed ( 0 , 2000 ); 16 } the else { . 17 Finish ( ); 18 is System.exit ( 0 ); . 19 } 20 is }