public class MainActivity extends Activity { private music.MyBinder mm;//在activity里面得到服务ibinder对象的引用 @Override protected 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{ @Override public void onServiceConnected(ComponentName name, IBinder service) { System.out.println("服务被绑定");//服务返回的ibinder对象会被传递给myconn的回调方法 mm= (MyBinder) service; } @Override public void onServiceDisconnected(ComponentName name) { } } public void music(View view){//利用ibinder对象间接的调用了服务里面的方法 mm.callchange("出发"); }
public class music extends Service { @Override public IBinder onBind(Intent intent) { System.out.println("服务绑定成功");//服务成功绑定的时候惠调用onbind方法返回一个ibinder对象 return new MyBinder(); } public class MyBinder extends Binder{ public void callchange(String name){//利用中间人代理 调用歌曲方法 classmusc(name); } } @Override public void onCreate() { System.out.println("服务被开启"); super.onCreate(); } public void classmusc(String Singname){ Toast.makeText(getApplicationContext(), "歌曲是"+Singname, 1).show(); } @Override public void onDestroy() { System.out.println("服务销毁"); super.onDestroy(); } }
原文地址:http://blog.csdn.net/a8903289/article/details/43497055