Exposing Your Interface to Clients

Now that you've got your interface implementation, you need to expose it to clients. This is known as "publishing your service." To publish a service, inherit Service and implement Service.onBind(Intent) to return an instance of the class that implements your interface. Here's a code snippet of a service that exposes the IRemoteService interface to clients.

public class RemoteService extends Service { @Override public IBinder onBind(Intent intent) {

// Select the interface to return. If your service only implements // a single interface, you can just return it here without checking // the Intent.

if (IRemoteService.class.getName().equals(intent.getAction())) { return mBinder;

if (ISecondary.class.getName().equals(intent.getAction())) { return mSecondaryBinder;

return null;

* The IRemoteInterface is defined through IDL */

private final IRemoteService.Stub mBinder = new IRemoteService.Stub() { public void registerCallback(IRemoteServiceCallback cb) { if (cb != null) mCallbacks.register(cb);

public void unregisterCallback(IRemoteServiceCallback cb) { if (cb != null) mCallbacks.unregister(cb);

* A secondary interface to the service.

private final ISecondary.Stub mSecondaryBinder = new ISecondary.Stub() { public int getPid() {

return Process.myPid();

public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) {

0 0

Post a comment