What does the Binder class do? What is the meaning of binding in Android bound services?

Mohit Gandhi picture Mohit Gandhi · May 4, 2017 · Viewed 7.7k times · Source

I am totally confused with bound services. My questions are:

  • What is the meaning of binding?
  • What does the Binder class do?
  • What is meant by "returns an IBinder for interacting with the service"?
  • What is the IBinder object?
  • How does the onBind() method work?

These are the a questions on bound services. Please explain in detail. I have already read the documentation, but it is still unclear to me.

Answer

Revan siddappa picture Revan siddappa · May 5, 2017

Bound service:

A bound service is one that allows application components to bind to it by calling bindService() to create a long-standing connection.

Create a bound service when you want to interact with the service from activities and other components in your application or to expose some of your application's functionality to other applications through interprocess communication (IPC).

To create a bound service, implement the onBind() callback method to return an IBinder that defines the interface for communication with the service. Other application components can then call bindService() to retrieve the interface and begin calling methods on the service. The service lives only to serve the application component that is bound to it, so when there are no components bound to the service, the system destroys it. You do not need to stop a bound service in the same way that you must when the service is started through onStartCommand().

IBinder:

To create a bound service, you must define the interface that specifies how a client can communicate with the service. This interface between the service and a client must be an implementation of IBinder and is what your service must return from the onBind() callback method. After the client receives the IBinder, it can begin interacting with the service through that interface.

onBind():

The system invokes this method by calling bindService() when another component wants to bind with the service (such as to perform RPC). In your implementation of this method, you must provide an interface that clients use to communicate with the service by returning an IBinder. You must always implement this method; however, if you don't want to allow binding, you should return null.