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 class MyService extends Service { private myreceiver receiver; @Override public IBinder onbind (Intent Intent) { //TODO auto-generated method stub return null; } private void Methodinservice () { Toast.maketext (this, "I am the method of service", Toast.length_long). Show () ; @Override public void OnCreate () { receiver = new Myreceiver (); Intentfilter filter = new Intentfilter (); Filter.addaction ("Com.yydcdut.braodcasttoservice"); Registerreceiver (receiver, filter); Super.oncreate (); } Private class Myreceiver extends Broadcastreceiver { @Override public void OnReceive (context context, Intent Intent) { System.out.println ("I am the broadcast recipient inside the service!!"); Methodinservice (); } } @Override public void OnDestroy () { 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.
Receiver = new Myreceiver (); Intentfilter filter = 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 class Mainactivity extends Activity { @Override protected void onCreate (Bundle savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); Intent Intent = new Intent (this,myservice.class); StartService (intent); } Button public void Call (view view) { Intent Intent = new Intent (); 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