Android系统进程间通信Binder机制在应用程序框架层的Java接口源代码分析(2)

简介:

这里我们可以看到IHelloService.aidl这个文件编译后的真面目,原来就是根据IHelloService接口的定义生成相应的Stub和Proxy类,这个就是我们熟悉的Binder机制的内容了,即实现这个HelloService的Server必须继续于这里的IHelloService.Stub类,而这个HelloService的远程接口就是这里的IHelloService.Stub.Proxy对象获得的IHelloService接口。接下来的内容,我们就可以看到IHelloService.Stub和IHelloService.Stub.Proxy是怎么创建或者使用的。
 

        三. HelloService的启动过程

        在讨论HelloService的启动过程之前,我们先来看一下实现HelloService接口的Server是怎么定义的。

        回忆在Ubuntu上为Android系统的Application Frameworks层增加硬件访问服务一文,我们在frameworks/base/services/java/com/android/server目录下新增了一个HelloService.java文件:

 

 
 
  1. package com.android.server;  
  2.  
  3. import android.content.Context;  
  4. import android.os.IHelloService;  
  5. import android.util.Slog;  
  6.  
  7. public class HelloService extends IHelloService.Stub {  
  8.     private static final String TAG = "HelloService";  
  9.  
  10.     HelloService() {  
  11.         init_native();  
  12.     }  
  13.  
  14.     public void setVal(int val) {  
  15.         setVal_native(val);  
  16.     }     
  17.  
  18.     public int getVal() {  
  19.         return getVal_native();  
  20.     }  
  21.       
  22.     private static native boolean init_native();  
  23.         private static native void setVal_native(int val);  
  24.     private static native int getVal_native();  

 这里,我们可以看到,HelloService继续了IHelloService.Stub类,它通过本地方法调用实现了getVal和setVal两个函数。我们不关心这两个函数的具体实现,有兴趣的读者可以参考在Ubuntu上为Android系统的Application Frameworks层增加硬件访问服务一文。
        有了HelloService这个Server类后,下一步就是考虑怎么样把它启动起来了。在frameworks/base/services/java/com/android/server/SystemServer.java文件中,定义了SystemServer类。SystemServer对象是在系统启动的时候创建的,它被创建的时候会启动一个线程来创建HelloService,并且把它添加到Service Manager中去。

       我们来看一下这部份的代码:

 

 
 
  1. class ServerThread extends Thread {  
  2.     ......  
  3.  
  4.     @Override  
  5.     public void run() {  
  6.  
  7.         ......  
  8.  
  9.         Looper.prepare();  
  10.  
  11.         ......  
  12.  
  13.         try {  
  14.             Slog.i(TAG, "Hello Service");  
  15.             ServiceManager.addService("hello", new HelloService());  
  16.         } catch (Throwable e) {  
  17.             Slog.e(TAG, "Failure starting Hello Service", e);  
  18.         }  
  19.  
  20.         ......  
  21.  
  22.         Looper.loop();  
  23.  
  24.         ......  
  25.     }  
  26. }  
  27.  
  28. ......  
  29.  
  30. public class SystemServer  
  31. {  
  32.     ......  
  33.  
  34.     /**  
  35.     * This method is called from Zygote to initialize the system. This will cause the native  
  36.     * services (SurfaceFlinger, AudioFlinger, etc..) to be started. After that it will call back  
  37.     * up into init2() to start the Android services.  
  38.     */  
  39.     native public static void init1(String[] args);  
  40.  
  41.     ......  
  42.  
  43.     public static final void init2() {  
  44.         Slog.i(TAG, "Entered the Android system server!");  
  45.         Thread thr = new ServerThread();  
  46.         thr.setName("android.server.ServerThread");  
  47.         thr.start();  
  48.     }  
  49.     ......  

  这里,我们可以看到,在ServerThread.run函数中,执行了下面代码把HelloService添加到Service Manager中去。这里我们关注把HelloService添加到Service Manager中去的代码:

 

 
 
  1. try {  
  2.     Slog.i(TAG, "Hello Service");  
  3.     ServiceManager.addService("hello", new HelloService());  
  4. } catch (Throwable e) {  
  5.     Slog.e(TAG, "Failure starting Hello Service", e);  

  通过调用ServiceManager.addService把一个HelloService实例添加到Service Manager中去。

         我们先来看一下HelloService的创建过程:

 

 
 
  1. new HelloService(); 

   这个语句会调用HelloService类的构造函数,而HelloService类继承于IHelloService.Stub类,IHelloService.Stub类又继承了Binder类,因此,最后会调用Binder类的构造函数:

 

 
 
  1. public class Binder implements IBinder {  
  2.     ......  
  3.       
  4.     private int mObject;  
  5.       
  6.     ......  
  7.  
  8.  
  9.     public Binder() {  
  10.         init();  
  11.         ......  
  12.     }  
  13.  
  14.  
  15.     private native final void init();  
  16.  
  17.  
  18.     ......  

 这里调用了一个JNI方法init来初始化这个Binder对象,这个JNI方法定义在frameworks/base/core/jni/android_util_Binder.cpp文件中:

 

 
 
  1. static void android_os_Binder_init(JNIEnv* env, jobject clazz)  
  2. {  
  3.     JavaBBinderHolder* jbh = new JavaBBinderHolder(env, clazz);  
  4.     if (jbh == NULL) {  
  5.         jniThrowException(env, "java/lang/OutOfMemoryError"NULL);  
  6.         return;  
  7.     }  
  8.     LOGV("Java Binder %p: acquiring first ref on holder %p", clazz, jbh);  
  9.     jbh->incStrong(clazz);  
  10.     env->SetIntField(clazz, gBinderOffsets.mObject, (int)jbh);  

它实际上只做了一件事情,就是创建一个JavaBBinderHolder对象jbh,然后把这个对象的地址保存在上面的Binder类的mObject成员变量中,后面我们会用到。
 

 

        回到ServerThread.run函数中,我们再来看一下ServiceManager.addService函数的实现:

 

 
 
  1. public final class ServiceManager {  
  2.     ......  
  3.  
  4.     private static IServiceManager sServiceManager;  
  5.  
  6.     ......  
  7.  
  8.     public static void addService(String name, IBinder service) {  
  9.         try {  
  10.             getIServiceManager().addService(name, service);  
  11.         } catch (RemoteException e) {  
  12.             Log.e(TAG, "error in addService", e);  
  13.         }  
  14.     }  
  15.  
  16.     ......  
  17.  

   这里的getIServiceManager函数我们在前面已经分析过了,它返回的是一个ServiceManagerProxy对象的IServiceManager接口。因此,我们进入到ServiceManagerProxy.addService中去看看:

 

 
 
  1. class ServiceManagerProxy implements IServiceManager {  
  2.     public ServiceManagerProxy(IBinder remote) {  
  3.         mRemote = remote;  
  4.     }  
  5.  
  6.     ......  
  7.  
  8.     public void addService(String name, IBinder service)  
  9.         throws RemoteException {  
  10.             Parcel data = Parcel.obtain();  
  11.             Parcel reply = Parcel.obtain();  
  12.             data.writeInterfaceToken(IServiceManager.descriptor);  
  13.             data.writeString(name);  
  14.             data.writeStrongBinder(service);  
  15.             mRemote.transact(ADD_SERVICE_TRANSACTION, data, reply, 0);  
  16.             reply.recycle();  
  17.             data.recycle();  
  18.     }  
  19.  
  20.     ......  
  21.  
  22.     private IBinder mRemote;  

这里的Parcel类是用Java来实现的,它跟我们前面几篇文章介绍Binder机制时提到的用C++实现的Parcel类的作用是一样的,即用来在两个进程之间传递数据。

       这里我们关注是如何把参数service写到data这个Parcel对象中去的:

 

 
 
  1. data.writeStrongBinder(service); 

我们来看看Parcel.writeStrongBinder函数的实现:

 

 
 
  1. public final class Parcel {  
  2.     ......  
  3.  
  4.     /**  
  5.     * Write an object into the parcel at the current dataPosition(),  
  6.     * growing dataCapacity() if needed.  
  7.     */  
  8.     public final native void writeStrongBinder(IBinder val);  
  9.  
  10.     ......  

这里的writeStrongBinder函数又是一个JNI方法,它定义在frameworks/base/core/jni/android_util_Binder.cpp文件中:

 

 
 
  1. static void android_os_Parcel_writeStrongBinder(JNIEnv* env, jobject clazz, jobject object)  
  2. {  
  3.     Parcel* parcel = parcelForJavaObject(env, clazz);  
  4.     if (parcel != NULL) {  
  5.         const status_t err = parcel->writeStrongBinder(ibinderForJavaObject(env, object));  
  6.         if (err != NO_ERROR) {  
  7.             jniThrowException(env, "java/lang/OutOfMemoryError"NULL);  
  8.         }  
  9.     }  

  这里的clazz参数是一个Java语言实现的Parcel对象,通过parcelForJavaObject把它转换成C++语言实现的Parcel对象。这个函数的实现我们就不看了,有兴趣的读者可以研究一下,这个函数也是实现在frameworks/base/core/jni/android_util_Binder.cpp这个文件中。
       这里的object参数是一个Java语言实现的Binder对象,在调用C++语言实现的Parcel::writeStrongBinder把这个对象写入到parcel对象时,首先通过ibinderForJavaObject函数把这个Java语言实现的Binder对象转换为C++语言实现的JavaBBinderHolder对象:

 

 
 
  1. sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj)  
  2. {  
  3.     if (obj == NULLreturn NULL;  
  4.  
  5.     if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {  
  6.         JavaBBinderHolder* jbh = (JavaBBinderHolder*)  
  7.             env->GetIntField(obj, gBinderOffsets.mObject);  
  8.         return jbh != NULL ? jbh->get(env) : NULL;  
  9.     }  
  10.  
  11.     if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {  
  12.         return (IBinder*)  
  13.             env->GetIntField(obj, gBinderProxyOffsets.mObject);  
  14.     }  
  15.  
  16.     LOGW("ibinderForJavaObject: %p is not a Binder object", obj);  
  17.     return NULL;  

我们知道,这里的obj参数是一个Binder类的实例,因此,这里会进入到第一个if语句中去。

         在前面创建HelloService对象,曾经在调用到HelloService的父类Binder中,曾经在JNI层创建了一个JavaBBinderHolder对象,然后把这个对象的地址保存在Binder类的mObject成员变量中,因此,这里把obj对象的mObject成员变量强制转为JavaBBinderHolder对象。

         到了这里,这个函数的功课还未完成,还剩下最后关键的一步:

 

 
 
  1. return jbh != NULL ? jbh->get(env) : NULL

   这里就是jbh->get这个语句了。

        在JavaBBinderHolder类中,有一个成员变量mBinder,它的类型为JavaBBinder,而JavaBBinder类继承于BBinder类。在前面学习Binder机制的C++语言实现时,我们在Android系统进程间通信(IPC)机制Binder中的Server启动过程源代码分析这篇文章中,曾经介绍过,IPCThreadState类负责与Binder驱动程序进行交互,它把从Binder驱动程序读出来的请求作简单的处理后,最后把这个请求扔给BBinder的onTransact函数来进一步处理。

        这里,我们就是要把JavaBBinderHolder里面的JavaBBinder类型Binder实体添加到Service Manager中去,以便使得这个HelloService有Client来请求服务时,由Binder驱动程序来唤醒这个Server线程,进而调用这个JavaBBinder类型Binder实体的onTransact函数来进一步处理,这个函数我们在后面会继续介绍。

       先来看一下JavaBBinderHolder::get函数的实现:

 

 
 
  1. class JavaBBinderHolder : public RefBase  
  2. {  
  3.     ......  
  4.  
  5.     JavaBBinderHolder(JNIEnv* env, jobject object)  
  6.         : mObject(object)  
  7.     {  
  8.         ......  
  9.     }  
  10.  
  11.     ......  
  12.  
  13.     sp<JavaBBinder> get(JNIEnv* env)  
  14.     {  
  15.         AutoMutex _l(mLock);  
  16.         sp<JavaBBinder> b = mBinder.promote();  
  17.         if (b == NULL) {  
  18.             b = new JavaBBinder(env, mObject);  
  19.             mBinder = b;  
  20.             ......  
  21.         }  
  22.  
  23.         return b;  
  24.     }  
  25.  
  26.     ......  
  27.  
  28.     jobject         mObject;  
  29.     wp<JavaBBinder> mBinder;  
  30. }; 

这里是第一次调用get函数,因此,会创建一个JavaBBinder对象,并且保存在mBinder成员变量中。注意,这里的mObject就是上面创建的HelloService对象了,这是一个Java对象。这个HelloService对象最终也会保存在JavaBBinder对象的成员变量mObject中。
 

       回到android_os_Parcel_writeStrongBinder函数中,下面这个语句:

 

 
 
  1. const status_t err = parcel->writeStrongBinder(ibinderForJavaObject(env, object)); 

    相当于是:

 

 
 
  1. const status_t err = parcel->writeStrongBinder((JavaBBinderHodler*)(obj.mObject)); 

因此,这里的效果相当于是写入了一个JavaBBinder类型的Binder实体到parcel中去。这与我们前面介绍的Binder机制的C++实现是一致的。

 

       接着,再回到ServiceManagerProxy.addService这个函数中,最后它通过其成员变量mRemote来执行进程间通信操作。前面我们在介绍如何获取Service Manager远程接口时提到,这里的mRemote成员变量实际上是一个BinderProxy对象,因此,我们再来看看BinderProxy.transact函数的实现:

 

 
 
  1. final class BinderProxy implements IBinder {  
  2.     ......  
  3.  
  4.     public native boolean transact(int code, Parcel data, Parcel reply,  
  5.                                 int flags) throws RemoteException;  
  6.  
  7.     ......  

  这里的transact成员函数又是一个JNI方法,它定义在frameworks/base/core/jni/android_util_Binder.cpp文件中:

 

 
 
  1. static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,  
  2.                         jint code, jobject dataObj,  
  3.                         jobject replyObj, jint flags)  
  4. {  
  5.     ......  
  6.  
  7.     Parcel* data = parcelForJavaObject(env, dataObj);  
  8.     if (data == NULL) {  
  9.         return JNI_FALSE;  
  10.     }  
  11.     Parcel* reply = parcelForJavaObject(env, replyObj);  
  12.     if (reply == NULL && replyObj != NULL) {  
  13.         return JNI_FALSE;  
  14.     }  
  15.  
  16.     IBinder* target = (IBinder*)  
  17.         env->GetIntField(obj, gBinderProxyOffsets.mObject);  
  18.     if (target == NULL) {  
  19.         jniThrowException(env, "java/lang/IllegalStateException""Binder has been finalized!");  
  20.         return JNI_FALSE;  
  21.     }  
  22.  
  23.     ......  
  24.  
  25.     status_t err = target->transact(code, *data, reply, flags);  
  26.  
  27.     ......  
  28.  
  29.     if (err == NO_ERROR) {  
  30.         return JNI_TRUE;  
  31.     } else if (err == UNKNOWN_TRANSACTION) {  
  32.         return JNI_FALSE;  
  33.     }  
  34.  
  35.     signalExceptionForError(env, obj, err);  
  36.     return JNI_FALSE;  

 这里传进来的参数dataObj和replyObj是一个Java接口实现的Parcel类,由于这里是JNI层,需要把它转换为C++实现的Parcel类,它们就是通过我们前面说的parcelForJavaObject函数进行转换的。
 

        前面我们在分析如何获取Service Manager远程接口时,曾经说到,在JNI层中,创建了一个BpBinder对象,它的句柄值为0,它的地址保存在gBinderProxyOffsets.mObject中,因此,这里通过下面语句得到这个BpBinder对象的IBinder接口:

 

 
 
  1. IBinder* target = (IBinder*)  
  2.         env->GetIntField(obj, gBinderProxyOffsets.mObject); 

 有了这个IBinder接口后,就和我们前面几篇文章介绍Binder机制的C/C++实现一致了。

        最后,通过BpBinder::transact函数进入到Binder驱动程序,然后Binder驱动程序唤醒Service Manager响应这个ADD_SERVICE_TRANSACTION请求:

 

 
 
  1. status_t err = target->transact(code, *data, reply, flags); 

具体可以参考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的远程接口:

 

 
 
  1. public class Hello extends Activity implements OnClickListener {    
  2.     ......   
  3.  
  4.     private IHelloService helloService = null;    
  5.  
  6.     ......  
  7.  
  8.     @Override    
  9.     public void onCreate(Bundle savedInstanceState) {    
  10.  
  11.         helloService = IHelloService.Stub.asInterface(    
  12.                             ServiceManager.getService("hello"));  
  13.     }  
  14.  
  15.     ......  

 我们先来看ServiceManager.getService的实现。前面我们说过,这里实际上是调用了ServiceManagerProxy.getService函数:

 

 
 
  1. class ServiceManagerProxy implements IServiceManager {  
  2.     public ServiceManagerProxy(IBinder remote) {  
  3.         mRemote = remote;  
  4.     }  
  5.  
  6.     ......  
  7.  
  8.     public IBinder getService(String name) throws RemoteException {  
  9.         Parcel data = Parcel.obtain();  
  10.         Parcel reply = Parcel.obtain();  
  11.         data.writeInterfaceToken(IServiceManager.descriptor);  
  12.         data.writeString(name);  
  13.         mRemote.transact(GET_SERVICE_TRANSACTION, data, reply, 0);  
  14.         IBinder binder = reply.readStrongBinder();  
  15.         reply.recycle();  
  16.         data.recycle();  
  17.         return binder;  
  18.     }  
  19.  
  20.     ......  
  21.  
  22.     private IBinder mRemote;  

最终通过mRemote.transact来执行实际操作。我们在前面已经介绍过了,这里的mRemote实际上是一个BinderProxy对象,它的transact成员函数是一个JNI方法,实现在frameworks/base/core/jni/android_util_Binder.cpp文件中的android_os_BinderProxy_transact函数中。

        这个函数前面我们已经看到了,这里就不再列出来了。不过,当这个函数从:

 

 
 
  1. status_t err = target->transact(code, *data, reply, flags); 

这里的reply变量里面就包括了一个HelloService的引用了。注意,这里的reply变量就是我们在ServiceManagerProxy.getService函数里面传进来的参数reply,它是一个Parcel对象。

       回到ServiceManagerProxy.getService函数中,从下面语句返回:

 

 
 
  1. mRemote.transact(GET_SERVICE_TRANSACTION, data, reply, 0); 

 接着,就通过下面语句将这个HelloService的引用读出来:

 

 
 
  1. IBinder binder = reply.readStrongBinder(); 

  我们看看Parcel.readStrongBinder的实现:

 

 
 
  1. public final class Parcel {  
  2.     ......  
  3.  
  4.     /**  
  5.     * Read an object from the parcel at the current dataPosition().  
  6.     */  
  7.     public final native IBinder readStrongBinder();  
  8.  
  9.     ......  

  它也是一个JNI方法,实现在frameworks/base/core/jni/android_util_Binder.cpp文件中:

 

 
 
  1. static jobject android_os_Parcel_readStrongBinder(JNIEnv* env, jobject clazz)  
  2. {  
  3.     Parcel* parcel = parcelForJavaObject(env, clazz);  
  4.     if (parcel != NULL) {  
  5.         return javaObjectForIBinder(env, parcel->readStrongBinder());  
  6.     }  
  7.     return NULL;  

这里首先把Java语言实现的Parcel对象class转换成C++语言实现的Parcel对象parcel,接着,通过parcel->readStrongBinder函数来获得一个Binder引用。

       我们在前面学习Binder机制时,在Android系统进程间通信(IPC)机制Binder中的Client获得Server远程接口过程源代码分析这篇文章中,曾经分析过这个函数,它最终返回来的是一个BpBinder对象,因此,下面的语句:

 

 
 
  1. return javaObjectForIBinder(env, parcel->readStrongBinder()); 

  就相当于是:

 

 
 
  1. return javaObjectForIBinder(env, new BpBinder(handle)); 

这里的handle就是HelloService这个Binder实体在Client进程中的句柄了,它是由Binder驱动程序设置的,上层不用关心它的值具体是多少。至于javaObjectForIBinder这个函数,我们前面介绍如何获取Service Manager的Java远程接口时已经有详细介绍,这里就不累述了,它的作用就是创建一个BinderProxy对象,并且把刚才获得的BpBinder对象的地址保存在这个BinderProxy对象的mObject成员变量中。

       最后返回到Hello.onCreate函数中,从下面语句返回:

 

 
 
  1. helloService = IHelloService.Stub.asInterface(    
  2.                     ServiceManager.getService("hello")); 

 就相当于是:

 

 
 
  1. helloService = IHelloService.Stub.asInterface(new BinderProxy())); 

回忆一下前面介绍IHelloService接口的定义时,IHelloService.Stub.asInterface是这样定义的:

 

 
 
  1. public interface IHelloService extends android.os.IInterface  
  2. {  
  3.     /** Local-side IPC implementation stub class. */  
  4.     public static abstract class Stub extends android.os.Binder implements android.os.IHelloService  
  5.     {  
  6.         ......  
  7.  
  8.         public static android.os.IHelloService asInterface(android.os.IBinder obj)  
  9.         {  
  10.             if ((obj==null)) {  
  11.                 return null;  
  12.             }  
  13.             android.os.IInterface iin = (android.os.IInterface)obj.queryLocalInterface(DESCRIPTOR);  
  14.             if (((iin!=null)&&(iin instanceof android.os.IHelloService))) {  
  15.                 return ((android.os.IHelloService)iin);  
  16.             }  
  17.             return new android.os.IHelloService.Stub.Proxy(obj);  
  18.         }  
  19.  
  20.         ......  
  21.     }  

   这里的obj是一个BinderProxy对象,它的queryLocalInterface返回null,于是调用下面语句获得HelloService的远程接口:

 

 
 
  1. return new android.os.IHelloService.Stub.Proxy(obj); 

   相当于是:

 

 
 
  1. return new android.os.IHelloService.Stub.Proxy(new BinderProxy()); 

 这样,我们就获得了HelloService的远程接口了,它实质上是一个实现了IHelloService接口的IHelloService.Stub.Proxy对象。

        五. Client通过HelloService的Java远程接口来使用HelloService提供的服务的过程

        上面介绍的Hello这个Activity获得了HelloService的远程接口后,就可以使用它的服务了。

        我们以使用IHelloService.getVal函数为例详细说明。在Hello::onClick函数中调用了IHelloService.getVal函数:

 

 
 
  1. public class Hello extends Activity implements OnClickListener {  
  2.     ......  
  3.  
  4.     @Override  
  5.     public void onClick(View v) {  
  6.         if(v.equals(readButton)) {  
  7.             int val = helloService.getVal();    
  8.             ......  
  9.         }  
  10.         else if(v.equals(writeButton)) {  
  11.             ......  
  12.         }  
  13.         else if(v.equals(clearButton)) {  
  14.             ......  
  15.         }  
  16.     }  
  17.  
  18.     ......  

 通知前面的分析,我们知道,这里的helloService接口实际上是一个IHelloService.Stub.Proxy对象,因此,我们进入到IHelloService.Stub.Proxy类的getVal函数中:

 

 
 
  1. public interface IHelloService extends android.os.IInterface  
  2. {  
  3.     /** Local-side IPC implementation stub class. */  
  4.     public static abstract class Stub extends android.os.Binder implements android.os.IHelloService  
  5.     {  
  6.           
  7.         ......  
  8.  
  9.         private static class Proxy implements android.os.IHelloService  
  10.         {  
  11.             private android.os.IBinder mRemote;  
  12.  
  13.             ......  
  14.  
  15.             public int getVal() throws android.os.RemoteException  
  16.             {  
  17.                 android.os.Parcel _data = android.os.Parcel.obtain();  
  18.                 android.os.Parcel _reply = android.os.Parcel.obtain();  
  19.                 int _result;  
  20.                 try {  
  21.                     _data.writeInterfaceToken(DESCRIPTOR);  
  22.                     mRemote.transact(Stub.TRANSACTION_getVal, _data, _reply, 0);  
  23.                     _reply.readException();  
  24.                     _result = _reply.readInt();  
  25.                 }  
  26.                 finally {  
  27.                     _reply.recycle();  
  28.                     _data.recycle();  
  29.                 }  
  30.                 return _result;  
  31.             }  
  32.         }  
  33.  
  34.         ......  
  35.         static final int TRANSACTION_getVal = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);  
  36.     }  
  37.  
  38.     ......  

 这里我们可以看出,实际上是通过mRemote.transact来请求HelloService执行TRANSACTION_getVal操作。这里的mRemote是一个BinderProxy对象,这是我们在前面获取HelloService的Java远程接口的过程中创建的。

        BinderProxy.transact函数是一个JNI方法,我们在前面已经介绍过了,这里不再累述。最过调用到Binder驱动程序,Binder驱动程序唤醒HelloService这个Server。前面我们在介绍HelloService的启动过程时,曾经提到,HelloService这个Server线程被唤醒之后,就会调用JavaBBinder类的onTransact函数:

 

 
 
  1. class JavaBBinder : public BBinder  
  2. {  
  3.     JavaBBinder(JNIEnv* env, jobject object)  
  4.         : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object))  
  5.     {  
  6.         ......  
  7.     }  
  8.  
  9.     ......  
  10.  
  11.     virtual status_t onTransact(  
  12.         uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0)  
  13.     {  
  14.         JNIEnv* env = javavm_to_jnienv(mVM);  
  15.  
  16.         ......  
  17.  
  18.         jboolean res = env->CallBooleanMethod(mObject, gBinderOffsets.mExecTransact,  
  19.             code, (int32_t)&data, (int32_t)reply, flags);  
  20.  
  21.         ......  
  22.  
  23.         return res != JNI_FALSE ? NO_ERROR : UNKNOWN_TRANSACTION;  
  24.     }  
  25.  
  26.     ......  
  27.  
  28.         JavaVM* const   mVM;  
  29.     jobject const   mObject;  
  30. }; 

  前面我们在介绍HelloService的启动过程时,曾经介绍过,JavaBBinder类里面的成员变量mObject就是HelloService类的一个实例对象了。因此,这里通过语句:

 

 
 
  1. jboolean res = env->CallBooleanMethod(mObject, gBinderOffsets.mExecTransact,  
  2.             code, (int32_t)&data, (int32_t)reply, flags); 

 就调用了HelloService.execTransact函数,而HelloService.execTransact函数继承了Binder类的execTransact函数:

 

 
 
  1. public class Binder implements IBinder {  
  2.     ......  
  3.  
  4.     // Entry point from android_util_Binder.cpp's onTransact  
  5.     private boolean execTransact(int code, int dataObj, int replyObj, int flags) {  
  6.         Parcel data = Parcel.obtain(dataObj);  
  7.         Parcel reply = Parcel.obtain(replyObj);  
  8.         // theoretically, we should call transact, which will call onTransact,  
  9.         // but all that does is rewind it, and we just got these from an IPC,  
  10.         // so we'll just call it directly.  
  11.         boolean res;  
  12.         try {  
  13.             res = onTransact(code, data, reply, flags);  
  14.         } catch (RemoteException e) {  
  15.             reply.writeException(e);  
  16.             res = true;  
  17.         } catch (RuntimeException e) {  
  18.             reply.writeException(e);  
  19.             res = true;  
  20.         } catch (OutOfMemoryError e) {  
  21.             RuntimeException re = new RuntimeException("Out of memory", e);  
  22.             reply.writeException(re);  
  23.             res = true;  
  24.         }  
  25.         reply.recycle();  
  26.         data.recycle();  
  27.         return res;  
  28.     }  

这里又调用了onTransact函数来作进一步处理。由于HelloService类继承了IHelloService.Stub类,而IHelloService.Stub类实现了onTransact函数,HelloService类没有实现,因此,最终调用了IHelloService.Stub.onTransact函数:

 

 
 
  1. public interface IHelloService extends android.os.IInterface  
  2. {  
  3.     /** Local-side IPC implementation stub class. */  
  4.     public static abstract class Stub extends android.os.Binder implements android.os.IHelloService  
  5.     {  
  6.         ......  
  7.  
  8.         @Override   
  9.         public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException  
  10.         {  
  11.             switch (code)  
  12.             {  
  13.             ......  
  14.             case TRANSACTION_getVal:  
  15.                 {  
  16.                     data.enforceInterface(DESCRIPTOR);  
  17.                     int _result = this.getVal();  
  18.                     reply.writeNoException();  
  19.                     reply.writeInt(_result);  
  20.                     return true;  
  21.                 }  
  22.             }  
  23.             return super.onTransact(code, data, reply, flags);  
  24.         }  
  25.  
  26.         ......  
  27.  
  28.     }  

  函数最终又调用了HelloService.getVal函数:

 

 
 
  1. public class HelloService extends IHelloService.Stub {  
  2.     ......  
  3.  
  4.     public int getVal() {  
  5.         return getVal_native();  
  6.     }  
  7.       
  8.     ......  
  9.     private static native int getVal_native();  

  最终,经过层层返回,就回到IHelloService.Stub.Proxy.getVal函数中来了,从下面语句返回:

 

 
 
  1. mRemote.transact(Stub.TRANSACTION_getVal, _data, _reply, 0); 

   并将结果读出来:

 

 
 
  1. _result = _reply.readInt(); 

 最后将这个结果返回到Hello.onClick函数中。

       这样,Client通过HelloService的Java远程接口来使用HelloService提供的服务的过程就介绍完了。

       至此,Android系统进程间通信Binder机制在应用程序框架层的Java接口源代码分析也完成了,整个Binder机制的学习就结束了。
 

       重新学习Android系统进程间通信Binder机制,请回到Android进程间通信(IPC)机制Binder简要介绍和学习计划一文。





本文转自 Luoshengyang 51CTO博客,原文链接:http://blog.51cto.com/shyluo/965299,如需转载请自行联系原作者

目录
相关文章
|
存储 安全 算法
【C++智能指针 相关应用】深入探索C++智能指针:跨进程、动态库与最佳实践
【C++智能指针 相关应用】深入探索C++智能指针:跨进程、动态库与最佳实践
61 5
|
26天前
|
开发框架 Java API
java反射机制的原理与简单使用
java反射机制的原理与简单使用
17 1
|
8天前
|
Java Maven
【Java报错】显示错误“Error:java: 程序包org.springframework.boot不存在“
【Java报错】显示错误“Error:java: 程序包org.springframework.boot不存在“
32 3
|
14天前
|
安全 Java 调度
深入理解Java中的线程安全与锁机制
【4月更文挑战第6天】 在并发编程领域,Java语言提供了强大的线程支持和同步机制来确保多线程环境下的数据一致性和线程安全性。本文将深入探讨Java中线程安全的概念、常见的线程安全问题以及如何使用不同的锁机制来解决这些问题。我们将从基本的synchronized关键字开始,到显式锁(如ReentrantLock),再到读写锁(ReadWriteLock)的讨论,并结合实例代码来展示它们在实际开发中的应用。通过本文,读者不仅能够理解线程安全的重要性,还能掌握如何有效地在Java中应用各种锁机制以保障程序的稳定运行。
|
19天前
|
Java 程序员 开发者
深入理解Java异常处理机制
在Java编程中,异常处理是确保程序健壮性与稳定性的重要组成部分。本文旨在深度剖析Java异常处理机制的核心概念、结构及其实际应用策略,帮助开发者更好地理解并运用异常处理来优化程序设计。我们将从Java异常体系结构入手,探讨try-catch-finally语句块的执行流程,分析自定义异常的必要性与实现方式,并通过实例演示如何有效地管理和处理异常情况。
23 3
|
23天前
|
Java
elasticsearch使用java程序添加删除修改
elasticsearch使用java程序添加删除修改
9 0
|
24天前
|
监控 Linux Shell
Linux 进程问题调查探秘:分析和排查频繁创建进程问题
Linux 进程问题调查探秘:分析和排查频繁创建进程问题
39 0
|
24天前
|
消息中间件 存储 网络协议
Linux IPC 进程间通讯方式的深入对比与分析和权衡
Linux IPC 进程间通讯方式的深入对比与分析和权衡
65 0
|
24天前
|
存储 算法 Linux
【Linux 系统标准 进程资源】Linux 创建一个最基本的进程所需的资源分析,以及线程资源与之的差异
【Linux 系统标准 进程资源】Linux 创建一个最基本的进程所需的资源分析,以及线程资源与之的差异
25 0
|
26天前
|
设计模式 XML 存储
java中的反射机制
java中的反射机制
12 1