界面如下
1在PlayerService活动中
PlayerService 继承 Service
Mediaplayer player;
{class Mybinder 继承 Binder{
public PlayerService getService()
return PlayerService.this;
}}
重写onCreate()player=MediaPlayer.create(this,Rr.raw.music);
重写 @Override
public IBinder onBind(Intent arg0) {
return new MyBinder();
}
public void play(){
player.start();
}
public void pause(){
player.pause();
}
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
player.stop();
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
player.release();
super.onDestroy();
}
2MainActivity
定义实例化
Button btnBind, btnUnBind, btnPlay, btnPause;
PlayerService playerService;
Intent intent;
PlayerServiceConnection conn = new PlayerServiceConnection();
intent = new Intent(MainActivity.this, PlayerService.class);
btnBind = (Button)findViewById(R.id.btn_bind);
btnUnBind = (Button)findViewById(R.id.btn_unbind);
btnPlay = (Button)findViewById(R.id.btn_play);
btnPause = (Button)findViewById(R.id.btn_pause);
PlayerClickListener pcl = new PlayerClickListener();
btnBind.setOnClickListener(pcl);
btnUnBind.setOnClickListener(pcl);
btnPlay.setOnClickListener(pcl);
btnPause.setOnClickListener(pcl);
class PlayerClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_bind:
//绑定服务
bindService(intent, conn, BIND_AUTO_CREATE);
break;
case R.id.btn_unbind:
unbindService(conn);
break;
case R.id.btn_play:
playerService.play();
break;
case R.id.btn_pause:
playerService.pause();
break;
}
class PlayerServiceConnection implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName arg0, IBinder binder) {
// TODO Auto-generated method stub
MyBinder myBinder = (PlayerService.MyBinder)binder;
playerService = myBinder.getService();
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
}
}
AndroidManifest
</activity>
<service android:name="com.niit.android_bindservice.PlayerService"></service>
</application>