Exit the app by double-clicking the Back button in Android
In Android apps, you can often exit applications by double-clicking the Back button, such as QQ space. The procedure is demonstrated by code below.
1. Set the exit glyph
Boolean isexist=false; default is Fasle
2. Overwrite the onkeydown () method
When you listen to the back key, when Keycode==keyevent.keycode_back executes, the isexist is set to Ture, and when you press the back key for the second time, the application exits, but the two time interval needs to be within a certain amount of time.
1 @Override2 Public BooleanOnKeyDown (intKeyCode, KeyEvent event) {3 if(keycode==keyevent.keycode_back) {4 if(!isexist) {5isexist=true;6Toast.maketext (Getapplicationcontext (), "Press again to exit the program", Toast.length_short). Show (); 7Handler.sendemptymessagedelayed (0,2000);8 return false;9 }Ten Else{ OneIntent intent=NewIntent (intent.action_main); A intent.addcategory (intent.category_home); - startactivity (intent); -System.exit (0); the } - } - return Super. OnKeyDown (KeyCode, event); -}
3. Set the Handler object
1 Private Handler handler=New Handler () {2public void handlemessage ( Android.os.Message msg) {3 isexist=false; // Cancel exit flag bit 4 }; 5 };
4. Basic Ideas
When under current activity, press the back key to get the event in OnKeyDown (), identify if it is the back key, and if it is the back key, set the exit flag Isexist to True. Then start the handler.sendemptymessagedelayed () method, send a message queue after 2 seconds, and in the message processing method, set the flag Isexist to False. If you press the back key again within 2 seconds, exit the application.
Android technology 23:android using the return key to exit the implementation