The service can be bound to the activity, which maintains a reference to the service instance, which allows you to make method calls to the running service as you would any other instantiation.
Allows service and activity bindings, which gives a more detailed interface. For a service to support binding, you need to implement the Onbind method and return the current instance of the service being bound.
Package Com.example.androidtest.service;import Android.app.service;import Android.content.intent;import Android.os.binder;import Android.os.ibinder;public class MyService extends Service {private final IBinder Binder = new MyB Inder (); @Overridepublic ibinder Onbind (Intent Intent) {//TODO auto-generated method Stubreturn Binder;} public class Mybinder extends Binder{myservice GetService () {return myservice.this;}} @Overridepublic void OnCreate () {//TODO auto-generated method Stubsuper.oncreate ();}}
The connection between the service and other components is represented as a serviceconnection.
To bind a service with other components, you need to implement a new serviceconnection, after establishing a connection, You can obtain a reference to the service by overriding the Onserviceconnected and Onservicedisconnectd methods. Program:
Package Com.example.androidtest;import Com.example.androidtest.service.myservice;import Android.os.Bundle;import Android.os.ibinder;import Android.app.activity;import Android.content.componentname;import android.content.Intent Import Android.content.serviceconnection;import Android.view.menu;public class Mainactivity extends Activity { Private MyService connection between Myservice;//service and activity private serviceconnection mconnection = new Serviceconnection () {@ overridepublic void onservicedisconnected (ComponentName arg0) {//TODO auto-generated method stubmyservice = null;} @Overridepublic void onserviceconnected (componentname className, IBinder service) {//When establishing a connection, call MyService = (( Myservice.mybinder) service). GetService ();}}; public void Tobind () {//bind a serviceintent bindintent = new Intent (mainactivity.this,myservice.class); Bindservice ( Bindintent, Mconnection, bind_auto_create);} @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.actiVity_main);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}