您的位置:首页 > 移动开发 > Android开发

android service 之 Binder

2015-07-31 00:00 405 查看
摘要: 通过binderService()启动服务

1,创建MusicPlayService继承Service

public class MusicPlayService extends Service{

}

2, 在MusicPlayService中创建内部类Mybinder继承Binder

public final class Mybinder extends Binder{
public MusicPlayService getService()
{
return  MusicPlayService.this;
}
}

3, 重写onBinder()方法,反回内部类Mybinder实例对象

public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return new Mybinder();
}

4,重写onCreate()

public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(this, "MusicSevice onCreate()" , Toast.LENGTH_SHORT).show();
Log.e("test", "--->onCreate()");
//musicplay=BackgroundMusicPlay.getBackgroundMusicPlay(this);
super.onCreate();
}

5,在activity中绑定service

MusicPlayService service;//声明服务对象
//绑定服务
Intent intent2=new Intent(ShorMusicPlay.this, MusicPlayService.class);
bindService(intent2, conn, BIND_AUTO_CREATE);
//调用服务,通过第6步中的 service=((Mybinder)arg1).getService();得到实例对象
service.playMusic();//playMusic可自行在MusicPlayService中添加

6,在ServiceConnection的onServiceConnected得到MusicPlayService的实例对象

private ServiceConnection conn=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// TODO Auto-generated method stub
Log.e("test", " on  Service  Connected");
service=((Mybinder)arg1).getService();//得到MusicPlayService实例对象
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
Log.e("test", " on  Service   Disconnected");
}
};

7,在onDestroy()方法中解除绑定

protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unbindService(conn);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息