Monday 16 June 2014

Android Bound Service Concept


Bound Service


Android bound service is a service component of an android application. Other component like, activity has to bind to this kind of service to initiate the communication between them. This is achieved via a method call of bindService() from activity class or whatever the other component is. Bound service will not run forever like “Started Service” and will be destroyed by the system once the caller is bind to it or you can say the caller has not called unbindService method. In my earlier post which has detail explanation about the android service. If you want to get a look over the service component please visit that page.



A bound service allows components (such as activities) to bind to the service, send requests, receive responses, and even perform inter-process communication (IPC). A bound service typically lives only while it serves another application component and does not run in the background indefinitely


This is kind of inter process communication (IPC) between android components like activity, broadcastreceiver or content provider and the bound service. In these kind of scenario bound services act as a SERVER and other component are clients. remember services are not restart on rotation of the device, it will stay to run the same instance unlike the activity. Bound services provides an interface for its client to access the public methods of the service. These public methods provide the actual service for its client. Client component like UI thread bind to this service using an Intent and ServiceConnection object to access it.


Lifetime of Bound Service


Bound Service live till at least one client component is bind to it. Suppose multiple clients are bind to it and this service is providing services to all these clients and some clients call unbindService but not all, then the service will have a life and it will still be running. As such, you don't have to manage the lifecycle of your service if it's purely a bound service—the Android system manages it for you based on whether it is bound to any clients.


Types of Bound Service


  • Local Bound Service
  • Remote Bound Service


A bound service can be a local or remote one. Before creating a bound service, you have to think some of the key points to implement this. Some of them are whether this bound service will be used within the same application or not. If it is like this then create a local bound service using IBinder class. Local bound service will run in the same process space in which service clients are running. So all the components are aware of this bound service.


A local bound service can be created using Binder class and for creating remote bound service you need either Messenger class or AIDL mechanism.


Second most important thing to consider is whether you want processing of clients requests in parallel or sequentially. To process requests parallely you have to create threads in such manner.  




Create Local Bound Service Using Binder


First let us create a skeleton to create a local bound service using Binder.


public class LocalBoundService extends Service {
  
// IBinder is the Interface between Client and Server which returns this service
  private final IBinder mBinder = new LocalBinder();

  private final Random gen = new Random();

  public class LocalBinder extends Binder {
      LocalBoundService getService() {
          // Return this instance of LocalService so clients can call public methods
          return LocalBoundService.this;
      }
  }

  @Override
  public IBinder onBind(Intent intent) {
      return mBinder;
  }

 // Public methods to be called by clients

  public int getRandomNumber() {
     return gen.nextInt(1000);
  }
}


In the above code snippet, a custom class LocalBoundService is created which extends the Service class. You need to override the onBind method of the service class which returns an IBinder instance on successful connection with the client. Client uses this binder to communicate the service. The binder instance that returns by the onBind method is assigned to a LocalBinder object which is a Binder type. Inside the LocalBinder, one method is defined, getService. Once client get the binder instance inside the ServiceConnection object, it returns the service itself to the client. The client now can call the public methods of the local service class. Below code snippet of the client which is an activity, uses this service to get  random number using the public method of the local service.


Create a Client for Local Bound Service


public class BindingActivity extends Activity {

// Define a Local Bound Service Reference
  LocalBoundService mService;
  boolean mBound = false;
  
  @Override
  protected void onStart() {
      super.onStart();
      Intent intent = new Intent(this, LocalService.class);
// Bind with the bound service with this activity component
      bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
  }

// Use the Local Service Reference to call public methods of Service
   public void onClick(View v){     
        int num = mService.getRandomNumber();    
   }          

//  Defines callbacks for service binding, passed to bindService()
  private ServiceConnection mConnection = new ServiceConnection() {
    @Override
   public void onServiceConnected(ComponentName className,
             IBinder service)
            {
                LocalBinder binder = (LocalBinder) service;
                mService = binder.getService();
                mBound = true;
       }
  };
}


Interaction Between Server and Client
Below diagram shows the interaction between client (Activity) and service component. Client needs a ServiceConnection Object to call bindService method. This bindService is asynchronous call, so you can get the immediate information about the successful connection with the service. This service connection information is received inside the onServiceConnected method of ServiceConnection object. On successful connection, you can call the public methods of the service. Once client is done with the service, it call unbindService method and system will destroy the service.


Create Remote Bound Service
  • Using Messenger
  • Using AIDL


A service can be accessed by another application also. To create such remote service android provide two mechanism. You can use Messenger class or use AIDL to implement these kind of services.we will discussed in next posts.




No comments:

Post a Comment