The above two functions are mainly referred to the blog:
http://blog.csdn.net/chenshijun0101/article/details/7682210
http://blog.csdn.net/winlinking/article/details/6596455
Method One:
Press the return key two times to exit the program:
Activity:
public class Back2finishappactivity extends Activity { Exit exit = new exit ();
/** called when the activity is first created. */ @Override public void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.main); }
@Override public boolean onKeyDown (int keycode, keyevent event) { if (keycode = = Keyevent.keycode_back) { Pressagainexit (); return true; }
Return Super.onkeydown (KeyCode, event); }
private void Pressagainexit () { if (Exit.isexit ()) { Finish (); } else { Toast.maketext (Getapplicationcontext (), "Press again to exit the program", Toast.length_short). Show (); Exit.doexitinonesecond (); } } } |
|
|
|
Auxiliary class Exit.java
Private Boolean isexit = false; Private Runnable task = new Runnable () { @Override public void Run () { Isexit = false; } };
public void Doexitinonesecond () { Isexit = true; Handlerthread thread = new Handlerthread ("Dotask"); Thread.Start (); New Handler (Thread.getlooper ()). postdelayed (Task, 1000); }
public Boolean isexit () { return isexit; }
public void Setexit (Boolean isexit) { This.isexit = Isexit; } |
|
|
|
Long press the back key to exit the program:
public boolean dispatchkeyevent (KeyEvent event) { int Keycode=event.getkeycode (); Switch (keycode) { Case Keyevent.keycode_back: { if (event.islongpress ()) { This.stopservice (Intent); System.exit (0); return true; }else { return false;
} } } Return Super.dispatchkeyevent (event);
} |
|
|
|
Method Two:
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 (), "Press again to exit the program", Toast.length_short). Show (); Exittime = System.currenttimemillis (); } else { Finish (); System.exit (0); } return true; } Return Super.onkeydown (KeyCode, event); } |
|
|
|
Android_ Press two times to exit the program and long press the return key to exit the program