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.L Ength_short). Show (); Exit.doexitinonesecond (); } } }
Auxiliary class Exit.java
Private Boolean isexit =False;Private Runnable task =NewRunnable () {@OverridePublicvoidRun () {isexit =False; } };PublicvoidDoexitinonesecond () {isexit =true; Handlerthread thread = new Handlerthread ("dotask"); Thread.Start (); New Handler (Thread.getlooper ()). postdelayed (Task, n);} 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 (keyeventEvent) {int keycode=Event. getKeyCode ();Switch (keycode) {case Keyevent.keycode_back: {if (event.islongpress ()) {this.stopservice (intent); System.exit (0return true; else {return falsereturn super.dispatchkeyevent (event); }
Method Two:
PrivateLong Exittime =0; @Overridepublic Boolean OnKeyDown (int KeyCode, KeyEventEvent) {if (keycode = = Keyevent.keycode_back &&Event.getaction () = = Keyevent.action_down) {if ((System.currenttimemillis ()-exittime) > 2000< Span style= "color: #000000;" ) {Toast.maketext (Getapplicationcontext (), " Press again to exit the program " System.currenttimemillis ();} else {finish (); System.exit (0return truereturn Super.onkeydown (keycode, event
Android_ Press two times to exit the program and long press the return key to exit the program