Sunday, May 31, 2015

Android Bound Services

A bound service is the server in the client-server interface. A Bound service allows a component such as Activities to bind a service, send requests, receive responses, and even perform interprocess communication (IPC). A Bound service typically lives only while it serves another application component and does not run in the background indefinitely. 

Below are the basics of it. 

Bind Service is an implementation of Service class. The subclass should implement the onBind callback method. It should return Binder object that defines programming interface that clients can use to communicate with the service. 

Clients can call bindService to bind to service, when it calls this method, it should provide a ServiceConnection implementation. When the Android system creates the service, it calls back the onServiceConnected method on the ServiceConnection to deliver the IBinder object. 


Multiple Clients can connect to the same service, however, how many ever connections, it will return same Binder object.

When the last client unbinds the service, the service get destroyed by the system. 

When creating a service that provides binding, the service must provide and Binder that provides programming interface that clients can use to interact with the service. There are three ways an IBinder can be created

1. Extending the Binder class 

If the Service is local to the application, then Service can create an Binder object which is extended from Binder class. The clients can call the public methods available on this Binder object to perform tasks. 

This is a preferred technique, if the service is merely the background worker for the application, 

2. Using a Messenger 

If the purpose is to work across different process, one can create interface for the service with Messenger. In this manner, service defines a Handler that responds to different types of Message objects. The handler is basis for a messenger that can share an IBinder with the client, allowing the client to send commands to the service using Message objects. Additionally the client can define a messenger of its own so the service can send message back. 

3. Using AIDL.

Messegener technique is based on AIDL, The Messenger creates queue of all the client requests in a single thread, so the service receives requests one at a time. However, if we want to service to handle multiple requests simultaneously, then AIDL can be used. In this case, service must be capable to handling multiple threads and built thread safe. Most of the apps should not use the AIDL. 



References:

No comments:

Post a Comment