In the Android application is we often have to judge the user to the return key operation, generally to prevent misoperation is the user repeatedly press two times the return button when the user is prompted to quit the application. There are many ways to do this by recording the time difference between key times:
Import android.app.Activity;
Import Android.os.Bundle;
Import android.view.KeyEvent;
Import Android.widget.Toast;
public class Mainactivity extends Activity {
Private long exittime = 0;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
}
@Override
public boolean onKeyDown (int keycode, keyevent event) {
; if (keycode = = keyevent.keycode_back) {
exit ();
return false;
}
return Super.onkeydown (KeyCode, event);
}
public void exit () {
if ((System.currenttimemillis ()-Exittime) > 2000) {
Toast.maketext (Getapplicationcontext (), "Press again to exit the program",
Toast.length_short). Show ();
Exittime = System.currenttimemillis ();
} else {
Finish ();
System.exit (0);
}
}
}
Android Press 2 times back key to exit program code