First, when acitivity and service are in the same application and process, they are implemented by inheriting the binder class.
When an Activity is bound to a service , it is responsible for maintaining a reference to the service instance, allowing you to make some method calls to the running service. For example, if you have a background music service in the background, you can use this method to communicate.
The code is as follows:
/*************************service Code ****************************************/ Public classLocalServiceextendsService {Private FinalIBinder Binder =NewLocalbinder (); Public classLocalbinderextendsBinder {LocalService getService () {returnLocalService. This; } } Publicibinder onbind (Intent Intent) {returnBinder; } } /*****************************activity Code *************************************/ Public classBindingactivityextendsActivity {LocalService LocalService; PrivateServiceconnection mconnection =Newserviceconnection () { Public voidonserviceconnected (componentname classname,ibinder localbinder) {LocalService=(Localbinder) localbinder.getservice (); } Public voidonservicedisconnected (componentname arg0) {LocalService=NULL; } }; protected voidOnStart () {Super. OnStart (); Intent Intent=NewIntent ( This, LocalService.class); Bindservice (Intent, mconnection, context.bind_auto_create); } protected voidOnStop () {Super. OnStop (); Unbindservice (mconnection); } Public voidprintrandomnumber{intnum =Localservice.getrandomnumber (); SYSTEM.OUT.PRINTLN (num); }}
Code Explanation:
Start service using Context.bindservice () Experience: Context.bindservice ()->oncreate ()->onbind ()->service running Onunbind (), OnDestroy ()->service stop
ActivityAble to bind thanks toServiceThe interface Onbind ().ServiceAndActivityThe connection of the serviceconnectionserviceconnectiononserviceconnected onservicedisconnected Execute the binding, call bindservice intent (explicit or implicit) and a instance. Once the connection is established, you will be able to access the service instance reference. once service object found,
Android Activity and service communication