Create a new class Doubleclickexithelper.java
public class doubleclickexithelper{private final activity mactivity;private boolean isonkeybacking;private handler mhandler;private toast mbacktoast;public Doubleclickexithelper (activity activity) {mactivity = activity;//Save the activitymhandler = passed in new handler (Looper.getmainlooper ());//Generate a Handler to manage Message Queuing}/** * activity onkeydown events * */public boolean onkeydown (int keycode, keyevent event) {if (keyCode != keyevent.keycode_back) {return false;} if (isonkeybacking) {mhandler.removecallbacks (onbacktimerunnable);//Remove Message Queue if (mbacktoast != null) {mbacktoast.cancel ();} Exit Mactivity.finish (); return true;} else{isonkeybacking = true;//Note that first executes here, because Isonkeybacking is just beginning to be falseif (mbacktoast == NULL) {Mbacktoast = toast.maketext (mactivity, r.string.back_exit_tips, 2000);} Mbacktoast.Show (); mhandler.postdelayed (onbacktimerunnable, 2000);//Join Message queue, execute return true after 2000ms;}} 2000ms after execution, set isonkeybacking to Falseprivate runnable onbacktimerunnable = new runnable () {@Overridepublic void run () {isonkeybacking = false;if (mBackToast != null) {mbacktoast.cancel ();}}};}
And then call it in the main interface.
Main.java
@Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.main);//Double-click the return key to exit Mdoubleclickexithelper = new Doubleclickexithelper (this);} /** * Listener return--whether to exit the program */public boolean onKeyDown (int keycode, KeyEvent event) {Boolean flag = true;if (keycode = = Keyevent.key Code_back) {//Whether exit application return Mdoubleclickexithelper.onkeydown (KeyCode, event);} else if (keycode = = Keyevent.keycode_menu) {//other}else if (keycode = = Keyevent.keycode_search) {//other}else{//other}return flag ;}
OK, so it can be done.
android--Double-click Back to exit the app