Bounded Service Android With Example | AndroidMonks

Bounded Service in Android – Complete Tutorial

If you are looking for a Service that can stick for the lifetime of a Activity and destroyed once the Activity is destroyed, bounded service is your answer. Service in Android mainly consists of Background, Foreground and Bounded Service.

In this tutorial we will see about Bounded Service and how to create and use them in our application.

Basics of a Bounded Service

The important thing to note here is that, creating any type of Service will need to use the Service Class. The bounded service means that we will be binding the Activity with the Service and this service will stay till the lifetime of the activity.

To provide binding for a service, you must implement the onBind() callback method. This method returns an IBinder object that defines the programming interface that clients can use to interact with the service.

We will see in detail about the Class creation and callback methods below. Follow the steps closely, we will create a very simple bounded service in no time!

Just like we saw about background service and Foreground Service, we can also start a Service and then bind our activity to it! This can be done by first calling the StartService() and then calling the bindService() method. It is however important to know that, if startService() is called, the service will start and bindService() will simply bind the Activity to the Service, once done, even after calling the unbindService() the Service will still be running unless stopService() is called!!

If you have gotten this point precisely we will jump on to learn some extra steps about creating our Binder Class.

Before doing that, lets create our BoundedService class like below. It has the same implementation as the Background and Foreground Service, except we have another method to override, the onBind() method!!

public class BoundedService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

What is the IBinder class we are using?

A client binds to a service by calling bindService(). When it does, it must provide an implementation of ServiceConnection(Which is another class implementation we will see below), 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. The Android system, creates the connection between the Service and the Activity using the ServiceConnection object! TheonServiceConnected() method includes an IBinder argument, which the client then uses to communicate with the bound service.

Various Ways to create our Connection between the Activity and the Service

There are 3 preferred ways to create a connection between the Service and Activity, they are listed below.

  • Extending the Binder class – Simple as it sounds, this is the most preferred way, you can create a simple Binder Class (Local class) connect the Activity with the IBinder Interface and pass the ServiceConnection object. If all of these words seem confusing to you, check the below image!
Related image
A Simple Binding Happening!

Now how is the IBinder coming into picture here! The IBinder acts as the interface that is the language the Service can understand. If the activity wants to ask for a question (In the above example for a random number), it sends the connection details through the IBinder interface which the service understands! You must have understood the connection by now.

  • Using a Messenger – Say you want the Service to work across different processes (Say a Service running remotely), we have to make use of the Inter Process Communication (Know more about it here). We can make use of Messenger in that case.
  • Using AIDL – It solves the same purpose as that of a Messenger except when we need to handle multi threaded requests( In terms of functionality both the Messenger and AIDL are the same)

Example Program to Create our Bounded Service

It is time to create our Bounded Service example. We will be seeing about extending the Binder Class below and how to effectively use that to create our Bounded Service.

I will be creating a Simple service to send Random Numbers whenever the Activity requests for it!

main_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:id="@+id/text_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Service Example"
        android:layout_marginTop="10dp" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/start"
        android:text="Request NUmber"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30dp"
        android:layout_gravity="center"
        android:id="@+id/serviceText"
        android:text="Center Text"/>
</LinearLayout>

ServiceActivity.java

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.w3c.dom.Text;

public class ServiceActivity extends Activity{
    BoundedService mBoundService;
    Boolean mServiceBound = false;
    Button startService;
    TextView serviceText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        startService = (Button) findViewById(R.id.start);
        serviceText = (TextView) findViewById(R.id.serviceText);

        startService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int randomNuber = mBoundService.genRandomNumber();
                serviceText.setText(String.valueOf(randomNuber));
            }
        });

    }
    @Override
    protected void onStart() {

        startService(new Intent(this, BoundedService.class));
        Intent intent = new Intent(this,BoundedService.class);
        bindService(intent,mServiceConnection, Context.BIND_AUTO_CREATE);
        super.onStart();
    }
    @Override
    protected void onStop() {
        unbindService(mServiceConnection);
        stopService(new Intent(this,BoundedService.class));
        super.onStop();
    }
    private ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mServiceBound = false;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            BoundedService.LocalBoundedService myBinder = (BoundedService.LocalBoundedService) service;
            mBoundService = myBinder.getService();
            mServiceBound = true;
        }
    };
}
BoundedService.java
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;

import java.util.Random;

public class BoundedService extends Service {
    private IBinder mBinder =  new LocalBoundedService();
    Random randomNumber = new Random();
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    @Override
    public boolean onUnbind(Intent intent) {

        return true;
    }
    public int genRandomNumber()
    {
        return randomNumber.nextInt(10000);
    }

    public class LocalBoundedService extends Binder {
        BoundedService getService() {
            return BoundedService.this;
        }
    }
}

Once you have implemented the above, do not forget to add the service in the manifest like below.

<service
    android:name=".ForegroundService"
    android:enabled="true" />
<service android:name=".BoundedService" />
Explanation

If you have been following me from the start, we saw what an IBinder class is, what a ServiceConnection is and most importantly how we will be sending and receiving data from Activity to Service.

From the above example in BoundedService.java class, we have created a LocalBoundedService class and extended the Binder class, this is going to act as the Interface we need to connect to the Service!

Inside the Class we have a getter() to return the Object of the BoundedService class.

Now jump back to the ServiceActivity.java class, we additionally have a private Class called the ServiceConnection which has the object mServiceConnection. This is going to provide us with a connection to the BoundedService class. How are we doing it? You guessed it right using the Interface we created in the above step! This interface will provide the mBoundeService with the class details of BoundedService class (This class holds the method we need to call, the genRandomNumber()).

Once the connection is through, our job is to merely use the mBounderService object to call the genRandomNumber() method. This will provide the value till the service is unbounded(We are unBinding it only in the onDestroy() method).

Final Application

After implementing all the steps, our final application looks like this!

Bounded Service Final Application
Bounded Service Final Application

Conclusion

The Bounded Service concept may seem overwhelming when compared to the Background and Foreground Services but is one of the most important concepts in the whole of Android Programming.

Drop in any comments you have below.

“Learn and Be Curious”

 

Leave a Comment