Android dynamic registration broadcast monitoring service Demo

Source: Internet
Author: User

Service class, be sure to register in the manifest file

 Public classLightserviceextendsService {Private BooleanIfrun =false; @Override Publicibinder onbind (Intent Intent) {//TODO auto-generated Method Stub        return NULL; } @Override Public voidonCreate () {Super. OnCreate (); System.out.println ("OnCreate"); }     Public voidOnStart (Intent Intent,intStartid) {        Super. OnStart (Intent, Startid); System.out.println ("OnStart"); if(ifrun) {return; } Timer Timer=NewTimer (); Timer.schedule (NewTimerTask () {@Override Public voidrun () {Intent Intent=NewIntent (); Intent.setaction ("Com.hnjd");            Sendbroadcast (Intent); }        }, 0, 2 * 1000); } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {        return Super. Onstartcommand (Intent, flags, Startid); } @Override Public voidOnDestroy () {Super. OnDestroy (); System.out.println ("OnDestroy"); Ifrun=false; }}

Broadcast Code

    class extends broadcastreceiver {        @Override        publicvoid  onreceive (context context, Intent Intent) {            System.out.println ("received broadcast ... ");            Jiexi ();        }    }

Dynamic registration of Broadcasts

PrivateMyboad B;PrivateIntentfilter Intentfilter;intentfilter=NewIntentfilter (); Intentfilter.addaction ("Com.hnjd");if(isChecked) {System.out.println ("Status Open"); Intent Intent=NewIntent (mainactivity. This, Lightservice.class);                    StartService (Intent);                Registerreceiver (b, Intentfilter); } Else{System.out.println ("Status Off");                    Unregisterreceiver (b); Intent Intent=NewIntent (mainactivity. This, Lightservice.class);                StopService (Intent); }

Android dynamic registration broadcast monitoring service Demo

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.