public class Mainactivity extends Activity {private music. Mybinder mm;//A reference to the service IBinder object in activity @overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);} public void open (view view) {Intent intent=new Intent (this,music.class); StartService (Intent); } public void Stop (view view) {Intent Intent =new Intent (this,music.class); StopService (Intent); public void Play (view view) {Intent Intent =new Intent (this,music.class); Bindservice (Intent,new myconn (), bind_auto_create); } Private class MyConn implements serviceconnection{@Overridepublic void onserviceconnected (componentname name, IBinder Service) {System.out.println ("services are Bound");//The IBinder object returned by the service is passed to MyConn's callback method mm= (mybinder) service; } @Overridepublic void onservicedisconnected (componentname name) {}} public void music (view view) {//using IBinder object indirectly Call the method inside the service Mm.callchange ("departure"); }
public class Music extends service {@Overridepublic IBinder onbind (Intent Intent) {System.out.println ("service binding succeeded");// When the service is successfully bound, the Onbind method returns a IBinder object return new Mybinder ();} public class Mybinder extends binder{public void Callchange (String name) {////Call song method with broker agent CLASSMUSC (name); } } @Overridepublic void OnCreate () {System.out.println ("service is turned on"); Super.oncreate ();} public void Classmusc (String singname) {Toast.maketext (Getapplicationcontext (), "Song is" +singname, 1). Show (); @Overridepublic void OnDestroy () {System.out.println ("service Destruction"); Super.ondestroy ();}}
How Android binds the service to invoke the service