Publishing an Interface

The server publishes an interface to make it possible for other activities to find it. Publishing is accomplished by overriding the onBind method of the Service class (described in "Android Service Lifecycle" on page 10).

A client calls the bindService method of the Context class, causing a call to the server's onBind method. The bindService and onBind methods are the "handshake" required to start using a remote interface in a specific Service object in a specific process running in the Android environment. Here is the example of an onBind implementation from the the class RemoteService in the ApiDemos application:

^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;

mBinder and mSecondaryBinder refer to objects implementing the Stub interface. You will see the implementation of mSecondaryBinder in the next section, where implementation of the Stub interface is explained. Let's take a look at this method in detail. First, the interface requested depends on matching the name of the interface, which is passed in the action parameter of the Intent object: if

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

In the client application looking for this interface, the contents of the Intent object were specified in a call to the bindService method of the Context class. That means that a program publishing a remote method interface must be a subclass of Service. But a program using a remote method interface can be any subclass of Context, including Activity and Service.

The Intent object is used to specify the interface. The class name of the interface is the action parameter of the Intent.

If the interface matches, the onBind method returns an IBinder instance, an instance of the Stub interface in the remote interface.

0 0

Post a comment