android BindService绑定服务

界面如下

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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值