Android technology 23:android using the return key to exit the implementation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.