Broadcast and service are one of Android's four main components.
The broadcast here is dynamic and registers itself with a broadcast.
The most typical use is to use the power-on broadcast, and then start their own services, that is, in the Android phone to open the boot.
Service and broadcast
Public classMyServiceextendsService {Privatemyreceiver Receiver; @Override Publicibinder onbind (Intent Intent) {//TODO Auto-generated method stubs return NULL; } Private voidMethodinservice () {Toast.maketext ( This, "I am the method of service", Toast.length_long). Show (); } @Override Public voidonCreate () {receiver=NewMyreceiver (); Intentfilter Filter=NewIntentfilter (); Filter.addaction ("Com.yydcdut.braodcasttoservice"); Registerreceiver (receiver, filter); Super. OnCreate (); } Private classMyreceiverextendsBroadcastreceiver {@Override Public voidOnReceive (Context context, Intent Intent) {System.out.println ("I'm a broadcast recipient inside the service!!"); Methodinservice (); }} @Override Public voidOnDestroy () {unregisterreceiver (receiver); Receiver=NULL; Super. OnDestroy (); }}
The myreceiver here is an internal class that does not register the build in Androidmanifest.xml, then it needs to perform the action of registering the broadcast.
New myreceiver (); New Intentfilter (); Filter.addaction ("Com.yydcdut.braodcasttoservice"); Registerreceiver (receiver, filter);
Intentfilter is the same as the manifest inside. Also register also have to write off, when this service destroy, write off the broadcast.
Mainactivity
Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Intent Intent=NewIntent ( This, MyService.class); StartService (Intent); } //Button Public voidCall (view view) {Intent Intent=NewIntent (); Intent.setaction ("Com.yydcdut.braodcasttoservice"); Sendbroadcast (Intent); }}
Com.yydcdut.braodcasttoservice This echo, the broadcast found this action.
I'm the dividing line of the king of the Land Tiger.
Source code: HTTP://PAN.BAIDU.COM/S/1DD1QX01
Method of invoking a service using a broadcast. zip
Reprint Please specify source: Http://www.cnblogs.com/yydcdut