Android进程间通信Binder机制

以下皆为个人理解,如有不妥之处请谅解。


首先是一些基础知识,IBinder 是一个接口 , Binder 是实现 IBinder的一个类;

写一个Binder类可以通过AIBL 或者自己手动,这里以AIDL为例 ;

以下是经过AIDL得到的Binder类代码结构(只写出重点部分,并不完整):



public interface infa extends android.os.IInterface 
{ 
    public static  abstract class Stub extends android.os.Binder implements infa 
      {
          public boolean onTransact(....)
            {...}
          private static class Proxy implements infa 
            {  private android.os.IBinder mRemote;
		clientMethod{  ... ;   mRemote.transact(); ...  };
	     }
       }
}


下面是Binder的执行流程:

服务端定义了Binder,而客户端的Binder一般由服务端Service的onBind()返回,那么两端都能调用执行Binder中的方法了;

  首先在客户端中的一个线程调用了Stub中Proxy的clientMethod();

  clientMethod()中创建了用于包装数据的Parcel对象,然后clientmethod还调用了一个transact()方法,在这个transact()中发起了远程调用请求

(此时客户端线程挂起), 这个远程调用请求使得服务端的一个线程调用服务端的Binder中的onTransact(),onTransact()中将clientmethod创建

  并传过来的Parcel对象进行处理,唤醒客户端线程,将parcel对象传回去给客户端线程,完成进程间的通信。

你可能感兴趣的:(Android进程间通信Binder机制)