Android press the return key again to exit the program

  • 2020-05-09 19:15:38
  • OfStack

It is necessary for the user to give a prompt before exiting the app, because maybe the user didn't really want to quit, but just accidentally pressed the return key by 1. Most apps give an Dialog before exiting the app, which I think is not very friendly, and the user has to move his finger to press the button in dialog. Personally, I think "press the return key again to exit the program" is best practice, and the implementation is also very simple, directly on the code:
 
private long exitTime = 0; 
@Override 
public boolean onKeyDown(int keyCode, KeyEvent event) { 
if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){ 
if((System.currentTimeMillis()-exitTime) > 2000){ 
Toast.makeText(getApplicationContext(), " then 1 Secondary exit procedure ", Toast.LENGTH_SHORT).show(); 
exitTime = System.currentTimeMillis(); 
} else { 
finish(); 
System.exit(0); 
} 
return true; 
} 
return super.onKeyDown(keyCode, event); 
} 

Related articles: