在前面几篇文章中,我们详细介绍了Android系统进程间通信机制Binder的原理,并且深入分析了系统提供的Binder运行库和驱动程序的源代码。细心的读者会发现,这几篇文章分析的Binder接口都是基于C/C++语言来实现的,但是我们在编写应用程序都是基于Java语言的,那么,我们如何使用Java语言来使用系统的Binder机制来进行进程间通信呢?这就是本文要介绍的Android系统应用程序框架层的用Java语言来实现的Binder接口了。
熟悉Android系统的读者,应该能想到应用程序框架中的基于Java语言的Binder接口是通过JNI来调用基于C/C++语言的Binder运行库来为Java应用程序提供进程间通信服务的了。JNI在Android系统中用得相当普遍,SDK中的Java接口API很多只是简单地通过JNI来调用底层的C/C++运行库从而为应用程序服务的。
这里,我们仍然是通过具体的例子来说明Binder机制在应用程序框架层中的Java接口,主要就是Service Manager、Server和Client这三个角色的实现了。通常,在应用程序中,我们都是把Server实现为Service的形式,并且通过IServiceManager.addService接口来把这个Service添加到Service Manager,Client也是通过IServiceManager.getService接口来获得Service接口,接着就可以使用这个Service提供的功能了,这个与运行时库的Binder接口是一致的。
前面我们学习Android硬件抽象层时,曾经在应用程序框架层中提供了一个硬件访问服务HelloService,这个Service运行在一个独立的进程中充当Server的角色,使用这个Service的Client运行在另一个进程中,它们之间就是通过Binder机制来通信的了。这里,我们就使用HelloService这个例子来分析Android系统进程间通信Binder机制在应用程序框架层的Java接口源代码。所以希望读者在阅读下面的内容之前,先了解一下前面在Ubuntu上为Android系统的Application Frameworks层增加硬件访问服务这篇文章。
这篇文章通过五个情景来学习Android系统进程间通信Binder机制在应用程序框架层的Java接口:1. 获取Service Manager的Java远程接口的过程;2. HelloService接口的定义;3. HelloService的启动过程;4. Client获取HelloService的Java远程接口的过程;5. Client通过HelloService的Java远程接口来使用HelloService提供的服务的过程。
一. 获取Service Manager的Java远程接口
我们要获取的Service Manager的Java远程接口是一个ServiceManagerProxy对象的IServiceManager接口。我们现在就来看看ServiceManagerProxy类是长什么样子的:
这里可以看出,ServiceManagerProxy类实现了IServiceManager接口,IServiceManager提供了getService和addService两个成员函数来管理系统中的Service。从ServiceManagerProxy类的构造函数可以看出,它需要一个BinderProxy对象的IBinder接口来作为参数。因此,要获取Service Manager的Java远程接口ServiceManagerProxy,首先要有一个BinderProxy对象。下面将会看到这个BinderProxy对象是如何获得的。
再来看一下是通过什么路径来获取Service Manager的Java远程接口ServiceManagerProxy的。这个主角就是ServiceManager了,我们也先看一下ServiceManager是长什么样子的:
ServiceManager类有一个静态成员函数getIServiceManager,它的作用就是用来获取Service Manager的Java远程接口了,而这个函数又是通过ServiceManagerNative来获取Service Manager的Java远程接口的。
接下来,我们就看一下ServiceManager.getIServiceManager这个函数的实现,这个函数定义在frameworks/base/core/java/android/os/ServiceManager.java文件中:
- public final class ServiceManager {
- ......
- private static IServiceManager sServiceManager;
- ......
- private static IServiceManager getIServiceManager() {
- if (sServiceManager != null) {
- return sServiceManager;
- }
- // Find the service manager
- sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());
- return sServiceManager;
- }
- ......
- }
如果其静态成员变量sServiceManager尚未创建,那么就调用ServiceManagerNative.asInterface函数来创建。在调用ServiceManagerNative.asInterface函数之前,首先要通过BinderInternal.getContextObject函数来获得一个BinderProxy对象。
我们来看一下BinderInternal.getContextObject的实现,这个函数定义在frameworks/base/core/java/com/android/internal/os/BinderInternal.java文件中:
- public class BinderInternal {
- ......
- /**
- * Return the global "context object" of the system. This is usually
- * an implementation of IServiceManager, which you can use to find
- * other services.
- */
- public static final native IBinder getContextObject();
- ......
- }
这里可以看出,BinderInternal.getContextObject是一个JNI方法,它实现在frameworks/base/core/jni/android_util_Binder.cpp文件中:
- static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
- {
- sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
- return javaObjectForIBinder(env, b);
- }
这里看到我们熟悉的ProcessState::self()->getContextObject函数,具体可以参考浅谈Android系统进程间通信(IPC)机制Binder中的Server和Client获得Service Manager接口之路一文。ProcessState::self()->getContextObject函数返回一个BpBinder对象,它的句柄值是0,即下面语句:
- sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
相当于是:
- sp<IBinder> b = new BpBinder(0);
接着调用javaObjectForIBinder把这个BpBinder对象转换成一个BinderProxy对象:
- jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
- {
- if (val == NULL) return NULL;
- if (val->checkSubclass(&gBinderOffsets)) {
- // One of our own!
- jobject object = static_cast<JavaBBinder*>(val.get())->object();
- //printf("objectForBinder %p: it's our own %p!\n", val.get(), object);
- return object;
- }
- // For the rest of the function we will hold this lock, to serialize
- // looking/creation of Java proxies for native Binder proxies.
- AutoMutex _l(mProxyLock);
- // Someone else's... do we know about it?
- jobject object = (jobject)val->findObject(&gBinderProxyOffsets);
- if (object != NULL) {
- jobject res = env->CallObjectMethod(object, gWeakReferenceOffsets.mGet);
- if (res != NULL) {
- LOGV("objectForBinder %p: found existing %p!\n", val.get(), res);
- return res;
- }
- LOGV("Proxy object %p of IBinder %p no longer in working set!!!", object, val.get());
- android_atomic_dec(&gNumProxyRefs);
- val->detachObject(&gBinderProxyOffsets);
- env->DeleteGlobalRef(object);
- }
- object = env->NewObject(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mConstructor);
- if (object != NULL) {
- LOGV("objectForBinder %p: created new %p!\n", val.get(), object);
- // The proxy holds a reference to the native object.
- env->SetIntField(object, gBinderProxyOffsets.mObject, (int)val.get());
- val->incStrong(object);
- // The native object needs to hold a weak reference back to the
- // proxy, so we can retrieve the same proxy if it is still active.
- jobject refObject = env->NewGlobalRef(
- env->GetObjectField(object, gBinderProxyOffsets.mSelf));
- val->attachObject(&gBinderProxyOffsets, refObject,
- jnienv_to_javavm(env), proxy_cleanup);
- // Note that a new object reference has been created.
- android_atomic_inc(&gNumProxyRefs);
- incRefsCreated(env);
- }
- return object;
- }
在介绍这个函数之前,先来看两个变量gBinderOffsets和gBinderProxyOffsets的定义。
先看gBinderOffsets的定义:
- static struct bindernative_offsets_t
- {
- // Class state.
- jclass mClass;
- jmethodID mExecTransact;
- // Object state.
- jfieldID mObject;
- } gBinderOffsets;
简单来说,gBinderOffsets变量是用来记录上面第二个类图中的Binder类的相关信息的,它是在注册Binder类的JNI方法的int_register_android_os_Binder函数初始化的:
- const char* const kBinderPathName = "android/os/Binder";
- static int int_register_android_os_Binder(JNIEnv* env)
- {
- jclass clazz;
- clazz = env->FindClass(kBinderPathName);
- LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.Binder");
- gBinderOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
- gBinderOffsets.mExecTransact
- = env->GetMethodID(clazz, "execTransact", "(IIII)Z");
- assert(gBinderOffsets.mExecTransact);
- gBinderOffsets.mObject
- = env->GetFieldID(clazz, "mObject", "I");
- assert(gBinderOffsets.mObject);
- return AndroidRuntime::registerNativeMethods(
- env, kBinderPathName,
- gBinderMethods, NELEM(gBinderMethods));
- }
再来看gBinderProxyOffsets的定义:
- static struct binderproxy_offsets_t
- {
- // Class state.
- jclass mClass;
- jmethodID mConstructor;
- jmethodID mSendDeathNotice;
- // Object state.
- jfieldID mObject;
- jfieldID mSelf;
- } gBinderProxyOffsets;
简单来说,gBinderProxyOffsets是用来变量是用来记录上面第一个图中的BinderProxy类的相关信息的,它是在注册BinderProxy类的JNI方法的int_register_android_os_BinderProxy函数初始化的:
- const char* const kBinderProxyPathName = "android/os/BinderProxy";
- static int int_register_android_os_BinderProxy(JNIEnv* env)
- {
- jclass clazz;
- clazz = env->FindClass("java/lang/ref/WeakReference");
- LOG_FATAL_IF(clazz == NULL, "Unable to find class java.lang.ref.WeakReference");
- gWeakReferenceOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
- gWeakReferenceOffsets.mGet
- = env->GetMethodID(clazz, "get", "()Ljava/lang/Object;");
- assert(gWeakReferenceOffsets.mGet);
- clazz = env->FindClass("java/lang/Error");
- LOG_FATAL_IF(clazz == NULL, "Unable to find class java.lang.Error");
- gErrorOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
- clazz = env->FindClass(kBinderProxyPathName);
- LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.BinderProxy");
- gBinderProxyOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
- gBinderProxyOffsets.mConstructor
- = env->GetMethodID(clazz, "<init>", "()V");
- assert(gBinderProxyOffsets.mConstructor);
- gBinderProxyOffsets.mSendDeathNotice
- = env->GetStaticMethodID(clazz, "sendDeathNotice", "(Landroid/os/IBinder$DeathRecipient;)V");
- assert(gBinderProxyOffsets.mSendDeathNotice);
- gBinderProxyOffsets.mObject
- = env->GetFieldID(clazz, "mObject", "I");
- assert(gBinderProxyOffsets.mObject);
- gBinderProxyOffsets.mSelf
- = env->GetFieldID(clazz, "mSelf", "Ljava/lang/ref/WeakReference;");
- assert(gBinderProxyOffsets.mSelf);
- return AndroidRuntime::registerNativeMethods(
- env, kBinderProxyPathName,
- gBinderProxyMethods, NELEM(gBinderProxyMethods));
- }
回到前面的javaObjectForIBinder函数中,下面这段代码:
- if (val->checkSubclass(&gBinderOffsets)) {
- // One of our own!
- jobject object = static_cast<JavaBBinder*>(val.get())->object();
- //printf("objectForBinder %p: it's our own %p!\n", val.get(), object);
- return object;
- }
前面说过,这里传进来的参数是一个BpBinder的指针,而BpBinder::checkSubclass继承于父类IBinder::checkSubclass,它什么也不做就返回false。
于是函数继续往下执行:
- jobject object = (jobject)val->findObject(&gBinderProxyOffsets);
由于这个BpBinder对象是第一创建,它里面什么对象也没有,因此,这里返回的object为NULL。
于是函数又继续往下执行:
- object = env->NewObject(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mConstructor);
这里,就创建了一个BinderProxy对象了。创建了之后,要把这个BpBinder对象和这个BinderProxy对象关联起来:
- env->SetIntField(object, gBinderProxyOffsets.mObject, (int)val.get());
就是通过BinderProxy.mObject成员变量来关联的了,BinderProxy.mObject成员变量记录了这个BpBinder对象的地址。
接下去,还要把它放到BpBinder里面去,下次就要使用时,就可以在上一步调用BpBinder::findObj把它找回来了:
- val->attachObject(&gBinderProxyOffsets, refObject,
- jnienv_to_javavm(env), proxy_cleanup);
最后,就把这个BinderProxy返回到android_os_BinderInternal_getContextObject函数,最终返回到最开始的ServiceManager.getIServiceManager函数中来了,于是,我们就获得一个BinderProxy对象了。
回到ServiceManager.getIServiceManager中,从下面语句返回:
- sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());
相当于是:
- sServiceManager = ServiceManagerNative.asInterface(new BinderProxy());
接下去就是调用ServiceManagerNative.asInterface函数了,这个函数定义在frameworks/base/core/java/android/os/ServiceManagerNative.java文件中:
- public abstract class ServiceManagerNative ......
- {
- ......
- static public IServiceManager asInterface(IBinder obj)
- {
- if (obj == null) {
- return null;
- }
- IServiceManager in =
- (IServiceManager)obj.queryLocalInterface(descriptor);
- if (in != null) {
- return in;
- }
- return new ServiceManagerProxy(obj);
- }
- ......
- }
这里的参数obj是一个BinderProxy对象,它的queryLocalInterface函数返回null。因此,最终以这个BinderProxy对象为参数创建一个ServiceManagerProxy对象。
返回到ServiceManager.getIServiceManager中,从下面语句返回:
- sServiceManager = ServiceManagerNative.asInterface(new BinderProxy());
就相当于是:
- sServiceManager = new ServiceManagerProxy(new BinderProxy());
于是,我们的目标终于完成了。
总结一下,就是在Java层,我们拥有了一个Service Manager远程接口ServiceManagerProxy,而这个ServiceManagerProxy对象在JNI层有一个句柄值为0的BpBinder对象与之通过gBinderProxyOffsets关联起来。
这样获取Service Manager的Java远程接口的过程就完成了。
二. HelloService接口的定义
前面我们在学习Android系统的硬件抽象层(HAL)时,在在Ubuntu上为Android系统的Application Frameworks层增加硬件访问服务这篇文章中,我们编写了一个硬件服务HelloService,它的服务接口定义在frameworks/base/core/java/android/os/IHelloService.aidl文件中:
- package android.os;
- interface IHelloService
- {
- void setVal(int val);
- int getVal();
- }
这个服务接口很简单,只有两个函数,分别用来读写硬件寄存器。
注意,这是一个aidl文件,编译后会生成一个IHelloService.java。我们来看一下这个文件的内容隐藏着什么奥秘,可以这么神奇地支持进程间通信。
- /*
- * This file is auto-generated. DO NOT MODIFY.
- * Original file: frameworks/base/core/java/android/os/IHelloService.aidl
- */
- package android.os;
- public interface IHelloService extends android.os.IInterface
- {
- /** Local-side IPC implementation stub class. */
- public static abstract class Stub extends android.os.Binder implements android.os.IHelloService
- {
- private static final java.lang.String DESCRIPTOR = "android.os.IHelloService";
- /** Construct the stub at attach it to the interface. */
- public Stub()
- {
- this.attachInterface(this, DESCRIPTOR);
- }
- /**
- * Cast an IBinder object into an android.os.IHelloService interface,
- * generating a proxy if needed.
- */
- public static android.os.IHelloService asInterface(android.os.IBinder obj)
- {
- if ((obj==null)) {
- return null;
- }
- android.os.IInterface iin = (android.os.IInterface)obj.queryLocalInterface(DESCRIPTOR);
- if (((iin!=null)&&(iin instanceof android.os.IHelloService))) {
- return ((android.os.IHelloService)iin);
- }
- return new android.os.IHelloService.Stub.Proxy(obj);
- }
- public android.os.IBinder asBinder()
- {
- return this;
- }
- @Override
- public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
- {
- switch (code)
- {
- case INTERFACE_TRANSACTION:
- {
- reply.writeString(DESCRIPTOR);
- return true;
- }
- case TRANSACTION_setVal:
- {
- data.enforceInterface(DESCRIPTOR);
- int _arg0;
- _arg0 = data.readInt();
- this.setVal(_arg0);
- reply.writeNoException();
- return true;
- }
- case TRANSACTION_getVal:
- {
- data.enforceInterface(DESCRIPTOR);
- int _result = this.getVal();
- reply.writeNoException();
- reply.writeInt(_result);
- return true;
- }
- }
- return super.onTransact(code, data, reply, flags);
- }
- private static class Proxy implements android.os.IHelloService
- {
- private android.os.IBinder mRemote;
- Proxy(android.os.IBinder remote)
- {
- mRemote = remote;
- }
- public android.os.IBinder asBinder()
- {
- return mRemote;
- }
- public java.lang.String getInterfaceDescriptor()
- {
- return DESCRIPTOR;
- }
- public void setVal(int val) throws android.os.RemoteException
- {
- android.os.Parcel _data = android.os.Parcel.obtain();
- android.os.Parcel _reply = android.os.Parcel.obtain();
- try {
- _data.writeInterfaceToken(DESCRIPTOR);
- _data.writeInt(val);
- mRemote.transact(Stub.TRANSACTION_setVal, _data, _reply, 0);
- _reply.readException();
- }
- finally {
- _reply.recycle();
- _data.recycle();
- }
- }
- public int getVal() throws android.os.RemoteException
- {
- android.os.Parcel _data = android.os.Parcel.obtain();
- android.os.Parcel _reply = android.os.Parcel.obtain();
- int _result;
- try {
- _data.writeInterfaceToken(DESCRIPTOR);
- mRemote.transact(Stub.TRANSACTION_getVal, _data, _reply, 0);
- _reply.readException();
- _result = _reply.readInt();
- }
- finally {
- _reply.recycle();
- _data.recycle();
- }
- return _result;
- }
- }
- static final int TRANSACTION_setVal = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
- static final int TRANSACTION_getVal = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
- }
- public void setVal(int val) throws android.os.RemoteException;
- public int getVal() throws android.os.RemoteException;
- }