Android: How to bind a service to call a service
Public class MainActivity extends Activity {private music. myBinder mm; // get the reference of the Service ibinder object in the 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, IBinder service) {System. out. println ("service bound"); // The ibinder object returned by the service will be passed to the callback method mm = (MyBinder) service;} @ Overridepublic void onServiceDisconnected (ComponentName name) of myconn) {}} public void music (View view) {// indirectly calls the method mm in the service using the ibinder object. callchange ("departure ");}
Public class music extends Service {@ Overridepublic IBinder onBind (Intent intent) {System. out. println ("service bound successfully"); // when the service is bound successfully, call the onbind method to return an ibinder object return new MyBinder ();} public class MyBinder extends Binder {public void callchange (String name) {// call the song method classmusc (name) ;}@ Overridepublic void onCreate () {System. out. println ("service enabled"); 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 ();}}