This is part 2 of the series.

Part 1 — Foreground Services

Part 3 — Intent Services

Bound Service.

To put into simple words, this type of service binds to a component(*s) such as an activity and return results back to them.

They are mostly used for long running operations and sometimes for never ending ones.

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.

When the last client unbinds from the service, the system destroys the service (unless the service was also started by startService()).

Learn By Doing

We’ll create a simple application that contains 3 buttons — Bind,Unbind and Print Button which sets the value of Textview to the elapsed time since the service began.

AndroidManifest.xml

Add the BoundService to the Manifest file.

activity_main.xml

Set up the activity_main.xml

BoundService.java

We need to access the public methods in this service.To do this we need a reference to service object instance.

We achieve this by creating a Binder subclass within the bound service class and extending it by adding one or more new methods that can be called by the client.We create a method getService() that returns the object instance.

MainActivity.java

Now let’s set up the Main Activity.

A client binds to a service by calling bindService(). When it does, it must provide an implementation of ServiceConnection, which monitors the connection with the service. The return value of bindService() indicates whether the requested service exists and whether the client is permitted access to it. When the Android system creates the connection between the client and service, it calls onServiceConnected() on the ServiceConnection. TheonServiceConnected() method includes an IBinder argument, which the client then uses to communicate with the bound service(Read More).

When unbind() is called the service is automatically terminated and OnDestroy() is called, This only happens if you use BIND_AUTO_CREATE in the BindService() method.

However, if the service is in Started State, (started using startService(intent)) then you’d have to call stopService(intent) to terminate the the service.

You can find this project on github.

--

--

No responses yet