Bound Services

http://developer.android.com/guide/components/bound-services.html

 

Bound Services通常是以CS的形式服务的,它一般只在被客户端需要的时候才存活,而不会一直存在于后台。

客户端想要绑定必须调用bindService(). 同时必须实现ServiceConnection接口,一旦绑定成功,就会调用接口的方法。

Multiple clients can connect to the service at once. However, the system calls your service's onBind() method to retrieve the IBinder only when the first client binds. The system then delivers the same IBinder to any additional clients that bind, without calling onBind() again.

  services的onbind方法只在第一次绑定的时候执行,后面其他客户端绑定的时候直接返回同一个ibinder。

 

当你创建一个Bound Services的时候,必须返回一个有效的IBinder提供接口使用,有三个方法可以返回有效IBinder:Extending the Binder class、Using a Messenger、Using AIDL。

 

Extending the Binder class

这种方法适用于:只给自己的程序用。

步骤:

Here's how to set it up:

  1. In your service, create an instance of Binder that either:
    • contains public methods that the client can call
    • returns the current Service instance, which has public methods the client can call
    • or, returns an instance of another class hosted by the service with public methods the client can call
  2. Return this instance of Binder from the onBind() callback method.
  3. In the client, receive the Binder from the onServiceConnected() callback method and make calls to the bound service using the methods provided.

  1、返回有公共方法使用的实例;2、在onBind返回这个实例;3、在客户端获取并使用;

  官方有代码,直接看。

 

Using a Messenger

这个是,如果该Services需要被多个程序调用的情况。

直接看官方代码吧,类似进程间通信。

 

文章最后还有总结,可以再看一下。

 

posted @ 2014-04-23 21:37  yutoulck  阅读(159)  评论(0编辑  收藏  举报