绑定服务主要是其他组件绑定服务(比如活动),然后发送请求,接收返回。这个服务主要是作为其他组件的佣人,不会再后台无限
地运行。个人认为关键要学习的是如何绑定以及服务和组件之间的通信。
如何绑定到服务
一个绑定的服务是Service类的实现,允许其他组件绑定和他通信。要为服务提供绑定,必须实现onBind回调方法。这个方法返回IBinder,
定义了客户端可以和服务通信的程序接口。
客户端可以调用bindService绑定到service上,要这么做必须提供ServiceConnection的实现,ServiceConnection监听和服务的连接。
bindService立马返回,没有值。但是当系统创建客户端和活动的连接的时候,系统调用ServiceConnection的onServiceConnected方法,
传送IBinder用来和服务通信。
多个客户端可以一次绑定到服务,然而系统在第一个客户端绑定的时候调用服务的onBind方法接收IBinder。然后把同一个IBinder传送给
其他客户端,不用在调用onBind。(很明显这个是系统帮我们处理,也就是说系统帮我们处理了很多)。
创建绑定服务
绑定服务最重要的就是在onBind回调方法定义接口。
有三种方式定义这个接口:
(1)如果服务是程序私有的,和客户端在同一个进程运行。继承Binder类,在onBind中返回他的一个实例。客户端接收这个Binder,可以直接访问Binder实现或服务的可用公共方法。
如果服务仅仅是我们程序的一个后台工作者,这是优先选择。只有我们的服务被其他应用使用或者跨进程才不使用这个方式。
这种方法应该是最常用。
(2)使用一个Messenger。如果要跨进程,需要使用Messenger。
(3)AIDL,不常用。
继承BInder最常用,我们学习下:
三部分:
- In your service, create an instance of
Binderthat either:- contains public methods that the client can call
- returns the current
Serviceinstance, which has public methods theclient can call - or, returns an instance of another class hosted by the service with public methods theclient can call
- Return this instance of
Binderfrom theonBind()callback method. - In the client, receive the
Binderfrom theonServiceConnected()callback method andmake calls to the bound service using the methods provided.
public class LocalService extends Service { // Binder given to clients private final IBinder mBinder = new LocalBinder(); // Random number generator private final Random mGenerator = new Random(); /** * Class used for the client Binder. Because we know this service always * runs in the same process as its clients, we don't need to deal with IPC. */ public class LocalBinder extends Binder { LocalService getService() { // Return this instance of LocalService so clients can call public methods return LocalService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } /** method for clients */ public int getRandomNumber() { return mGenerator.nextInt(100); } }
绑定服务的区别就是可以获得访问服务的方法的能力,通过从Binder获取返回的服务实例。

被折叠的 条评论
为什么被折叠?



