具体可以参考Android系统进程间通信(IPC)机制Binder中的Server启动过程源代码分析一文。需要注意的是,这里的data包含了一个JavaBBinderHolder类型的Binder实体对象,它就代表了我们上面创建的HelloService。Service Manager收到这个ADD_SERVICE_TRANSACTION请求时,就会把这个Binder实体纳入到自己内部进行管理。
这样,实现HelloService的Server的启动过程就完成了。
四. Client获取HelloService的Java远程接口的过程
前面我们在学习Android系统硬件抽象层(HAL)时,在在Ubuntu上为Android系统内置Java应用程序测试Application Frameworks层的硬件服务这篇文章中,我们创建了一个应用程序,这个应用程序作为一个Client角色,借助Service Manager这个Java远程接口来获得HelloService的远程接口,进而调用HelloService提供的服务。
我们看看它是如何借助Service Manager这个Java远程接口来获得HelloService的远程接口的。在Hello这个Activity的onCreate函数,通过IServiceManager.getService函数来获得HelloService的远程接口:
- public class Hello extends Activity implements OnClickListener {
- ......
- private IHelloService helloService = null;
- ......
- @Override
- public void onCreate(Bundle savedInstanceState) {
- helloService = IHelloService.Stub.asInterface(
- ServiceManager.getService("hello"));
- }
- ......
- }
我们先来看ServiceManager.getService的实现。前面我们说过,这里实际上是调用了ServiceManagerProxy.getService函数:
- class ServiceManagerProxy implements IServiceManager {
- public ServiceManagerProxy(IBinder remote) {
- mRemote = remote;
- }
- ......
- public IBinder getService(String name) throws RemoteException {
- Parcel data = Parcel.obtain();
- Parcel reply = Parcel.obtain();
- data.writeInterfaceToken(IServiceManager.descriptor);
- data.writeString(name);
- mRemote.transact(GET_SERVICE_TRANSACTION, data, reply, 0);
- IBinder binder = reply.readStrongBinder();
- reply.recycle();
- data.recycle();
- return binder;
- }
- ......
- private IBinder mRemote;
- }
最终通过mRemote.transact来执行实际操作。我们在前面已经介绍过了,这里的mRemote实际上是一个BinderProxy对象,它的transact成员函数是一个JNI方法,实现在frameworks/base/core/jni/android_util_Binder.cpp文件中的android_os_BinderProxy_transact函数中。
这个函数前面我们已经看到了,这里就不再列出来了。不过,当这个函数从:
- status_t err = target->transact(code, *data, reply, flags);
这里的reply变量里面就包括了一个HelloService的引用了。注意,这里的reply变量就是我们在ServiceManagerProxy.getService函数里面传进来的参数reply,它是一个Parcel对象。
回到ServiceManagerProxy.getService函数中,从下面语句返回:
- mRemote.transact(GET_SERVICE_TRANSACTION, data, reply, 0);
接着,就通过下面语句将这个HelloService的引用读出来:
- IBinder binder = reply.readStrongBinder();
我们看看Parcel.readStrongBinder的实现:
- public final class Parcel {
- ......
- /**
- * Read an object from the parcel at the current dataPosition().
- */
- public final native IBinder readStrongBinder();
- ......
- }
它也是一个JNI方法,实现在frameworks/base/core/jni/android_util_Binder.cpp文件中:
- static jobject android_os_Parcel_readStrongBinder(JNIEnv* env, jobject clazz)
- {
- Parcel* parcel = parcelForJavaObject(env, clazz);
- if (parcel != NULL) {
- return javaObjectForIBinder(env, parcel->readStrongBinder());
- }
- return NULL;
- }
