Now the app is more and more humane, in order to meet the user's desire to experience, from all aspects have been carefully dealt with. For example, when we click the first click on the Back button, it will be warmly prompted " press the return key to exit the application ", and so on, today to record their own in the project to write this small function:
First write a tool class:
public class Doubleclickexitapp {private Context mcontext; /**whether it is to click againBackKey*/Private Boolean isonkeyback; Private Handler Mhandler; /**Exit Tipstoast*/private Toast Mexittoast; Public Doubleclickexitapp (Context context) {This.mcontext = context; This.mhandler = new Handler (Looper.Getmainlooper()); } /**whereActivityClick Back to event handling in the*/public boolean onKeyDown (int keycode, keyevent event) {if (keycode! = KeyEvent.Keycode_back) {//If the return key is not clicked, the returnFalse to return false; } if (Isonkeyback) {mhandler.removecallbacks (onbackexitrunnable); if (mexittoast! = null) {Mexittoast.cancel (); } /**Direct Exit*/AppManager.Getappmanager(). AppExit (Mcontext); return true; } else {isonkeyback = true; if (mexittoast = = null) {Mexittoast = Toast.Maketext(Mcontext, "Press the back key again to exit the app", Toast.Length_short); } mexittoast.show (); Mhandler.postdelayed (Onbackexitrunnable, 2000); return true; }} private Runnable onbackexitrunnable = new Runnable () {@Override public void run () {Isonkeyback = false; if (mexittoast! = null) {Mexittoast.cancel (); } } };}
It is then called directly in the corresponding activity or main page:
public Class Mainactivity extends activity{private Doubleclickexitapp mdoubleclickexitapp; @Override protected void onCreate (Bundle savedinstancestate) {su Per.oncreate (savedinstancestate); Setcontentview (r.layout. Activity_main ); Mdoubleclickexitapp = new Doubleclickexitapp (this);
} @Override protected void OnDestroy () {Super.ondestroy (); }/** the tool class method that we wrote in handling the OnKeyDown event can be */@Override public boolean onKeyDown (int keycode, keyevent event) {if ( KeyCode = = KeyEvent. keycode_back ) {return Mdoubleclickexitapp.onkeydown (KeyCode, event); }else{
Return Super.onkeydown (KeyCode, event);
}
}
Click the Back button in the app to exit the app