Android Monitor Home button

Source: Internet
Author: User

The game needs to count the user to exit the game is to press the return key or home, because the return key is their own cocos2dx to do the monitoring, so here say the Android activity listening Home key method, pro-test is available, here to do a backup which is also reference to other people's Code implementation, Path does not remember, if there is similar, hope forgive me ...

Here is a way to listen to the home operation in the form of a broadcast:

First, add the following broadcast in Mainactivity to generate a member variable:

 private final broadcastreceiver homereceiver = new broadcastreceiver ()  {      final String SYS_KEY =  "Reason";  // Label it must be such a string value       final String SYS_HOME_KEY =  "HomeKey" ;//Label It must be such a string value          @Override        public void onreceive (context context, intent intent)  {         string action = intent.getaction ();        if  (Action.equals (intent.action_close_system_dialogs)) {             string reason = intent.getstringextra (SYS_KEY);             if  (reason != null &&  reason.equals (Sys_home_kEY)) {             log.i ("TT",  "######### ######## #home键监听 ");                          }          }      } };

Then add the following method to the OnCreate method:

Intentfilter homefilter = new Intentfilter (intent.action_close_system_dialogs); Registerreceiver (Homereceiver, Homefilter);

Note When the app exits, remember to unregister the broadcast in the activity's OnDestroy method:

@Override protected void OnDestroy () {Super.ondestroy ();           if (homereceiver! = null) {try{unregisterreceiver (homereceiver);           }catch (Exception e) {log.e ("TT", "Unregisterreceiver homereceiver failure:" +e.getcause ()); }        }    }

Android Monitor Home button

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.