我对绑定服务完全感到困惑。我的问题是:
- 什么是绑定?
- Binder类是做什么的?
- "返回可用于与服务交互的IBinder"是什么意思?
- 什么是IBinder对象?
- onBind()方法如何工作?
绑定服务:
绑定服务允许应用程序组件通过调用bindService()方法来创建长期连接并与之绑定。当您想从应用程序中的活动和其他组件与服务进行交互,或者通过进程间通信(IPC)向其他应用程序公开应用程序功能时,请创建绑定服务。
要创建绑定服务,请实现onBind()回调方法以返回定义与服务通信接口的IBinder。其他应用程序组件可以通过调用 bindService() 方法来检索该接口,并开始在服务上调用方法。服务仅存在于绑定到它的应用程序组件的生命周期内,因此当没有组件绑定到服务时,系统将销毁该服务。您不需要像启动onStartCommand()服务时那样停止绑定服务。
IBinder:
要创建绑定服务,必须定义指定客户端如何与服务通信的接口。这个服务和客户端之间的接口必须是IBinder的一个实现,并且必须从onBind()回调方法中返回。客户端接收到IBinder之后,就可以通过该接口开始与服务进行交互。
onBind():
当另一个组件想要绑定服务(例如执行RPC)时,系统会通过调用bindService()方法来调用此方法。在此方法的实现中,您必须提供客户端用于与服务通信的接口,并返回IBinder。您必须始终实现此方法;但是,如果您不想允许绑定,则应返回null。
这是上面答案的一个例子
**代码将为您清晰地解释**
public class MyServiceClass extends Service {
//binder given to client
private final IBinder mBinder = new LocalBinder();
//our inner class
public LocalBinder extends Binder {
public MyServiceClass getService() {
return MyServiceClass.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public void doSomeWork(int time){ //we will call this function from outside, which is the whole idea of this **Binding**}
}
Defines callbacks for service binding, passed to bindService()
private ServiceConnection serviceConnection = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
MyServiceClass.LocalBinder binder =(MyServiceClass.LocalBinder)service;
timerService = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
//what to do if service diconnect
}
};
the moment of binding
Intent intent = new Intent(this, MyServiceClass.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
unbindService(serviceConnection);
timerService.doSomeWork(50);