In the app that uses Android platform is we often find that click two times the return key will prompt whether to exit the function, the following talk about how this function is implemented (this method is relatively simple)
The first method is to listen to the system return key, define a variable to record the key time, by calculating the timing to achieve the function, the code is as follows:
//Time on Exit
Private long mexittime;
Listens on the return key
@Override
Public boolean onKeyDown (int keycode, keyevent event) {
if (keycode = = KEYEVENT.KEYC Ode_back && event.getrepeatcount () = = 0) {
exit ();
return true;
}
Return Super.onkeydown (KeyCode, event);
}
public void exit () {
if ((System.currenttimemillis ()-Mexittime) >) {
Toast.maketext (Ma Inactivity.this, "Press again to exit the Daily News", Toast.length_short). Show ();
Mexittime = System.currenttimemillis ();
} else {
Myconfig.clearsharepre (this, "users");
Finish ();
System.exit (0);
}
}
The basic principle of the second implementation is that when the back key is pressed, the onkeydown is captured and the back key is determined, then the exit method is executed.
in the Exit method, the value of Isexit is first judged, if False, it is set to true, and a prompt pops up, and a message is issued after 2000 milliseconds (2 seconds), and this value is reverted to false in handler. If the back key is pressed again within 2 seconds of the sending message interval, the exit method is executed again, and the exit method is executed when the value of Isexit is true.
Import Android.app.activity;import android.os.bundle;import Android.os.handler;import Android.os.Message;import Android.view.keyevent;import Android.widget.toast;public class Mainactivity extends Activity {//define a variable to identify whether to exit the PRI Vate static Boolean isexit = false; Handler Mhandler = new Handler () {@Override public void Handlemessage (Message msg) {Super.handl EMessage (msg); Isexit = false; } }; @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); private void Exit () {if (!isexit) {isexit = true; Toast.maketext (Getapplicationcontext (), "Press again to exit the program", Toast. Length_short). Show (); Use handler delay to send Change status information mhandler.sendemptymessagedelayed (0, 2000); } else {finish (); System.exit (0); } }}
Android realizes the Exit function by clicking the two-time return key