Remote Service

Services typically are required to run for a long time and hence should run in their own thread. Such services can be invoked by any number of clients who want to connect to the service, invoke a few methods on the service and finally release the service, probably to serve more clients or close down.



The difference between the two mainly is that the local service runs in the same process as the application that started it and hence the life of the local service is dependent on the life of the said application while remote service can run in its own process. This causes a challenge of inter-process communication. If one process wants to communicate with another process, the object that is passed between the two needs to be marshaled.



The service has to declare a service interface in an aidl file and the AIDL tool will automatically create a java interface corresponding to the aidl file. The AIDL tool also generates a stub class that provides an abstract implementation of the service interface methods. The actual service class will have to extend this stub class to provide the real implementation of the methods exposed through the interface.

The service clients will have to invoke the onBind() method on the service to be able to connect to the service. The onBind() method returns an object of the stub class to the client. Here are the code related code snippets:

The AIDL file:
package com.collabera.labs.sai;

interface IMyRemoteService {

int getCounter();
}

Once you write this AIDL file (.aidl) in eclipse, it will automatically generate the Remote interface corresponding to this file. The remote interface will also provide a stub inner class which has to have an implementation provided by the RemoteService class. The stub class implementation within the service class is as given here:

private IMyRemoteService.Stub myRemoteServiceStub = new IMyRemoteService.Stub() {
public int getCounter() throws RemoteException {
return counter;
}
};
The onBind() method in the service class:
public IBinder onBind(Intent arg0) {
Log.d(getClass().getSimpleName(), "onBind()");
return myRemoteServiceStub;
}

Comments

Popular Posts