Client
进程 将参数(整数a和b)发送到Server
进程
/ 1. Client进程 将需要传送的数据写入到Parcel对象中
// data = 数据 = 目标方法的参数(Client进程传进来的,此处就是整数a和b) + IInterface接口对象的标识符descriptor
android.os.Parcel data = android.os.Parcel.obtain();
data.writeInt(a);
data.writeInt(b);
data.writeInterfaceToken("add two int");;
// 方法对象标识符让Server进程在Binder对象中根据"add two int"通过queryLocalIInterface()查找相应的IInterface对象(即Server创建的plus),Client进程需要调用的相加方法就在该对象中
android.os.Parcel reply = android.os.Parcel.obtain();
// reply:目标方法执行后的结果(此处是相加后的结果)
// 2. 通过 调用代理对象的transact() 将 上述数据发送到Binder驱动
binderproxy.transact(Stub.add, data, reply, 0)
// 参数说明:
// 1. Stub.add:目标方法的标识符(Client进程 和 Server进程 自身约定,可为任意)
// 2. data :上述的Parcel对象
// 3. reply:返回结果
// 0:可不管
// 注:在发送数据后,Client进程的该线程会暂时被挂起
// 所以,若Server进程执行的耗时操作,请不要使用主线程,以防止ANR
// 3. Binder驱动根据 代理对象 找到对应的真身Binder对象所在的Server 进程(系统自动执行)
// 4. Binder驱动把 数据 发送到Server 进程中,并通知Server 进程执行解包(系统自动执行)
Server
进程根据Client
进要求 调用 目标方法(即加法函数)
// 1. 收到Binder驱动通知后,Server 进程通过回调Binder对象onTransact()进行数据解包 & 调用目标方法
public class Stub extends Binder {
// 复写onTransact()
@Override
boolean onTransact(int code, Parcel data, Parcel reply, int flags){
// code即在transact()中约定的目标方法的标识符
switch (code) {
case Stub.add: {
// a. 解包Parcel中的数据
data.enforceInterface("add two int");
// a1. 解析目标方法对象的标识符
int arg0 = data.readInt();
int arg1 = data.readInt();
// a2. 获得目标方法的参数
// b. 根据"add two int"通过queryLocalIInterface()获取相应的IInterface对象(即Server创建的plus)的引用,通过该对象引用调用方法
int result = this.queryLocalIInterface("add two int") .add( arg0, arg1);
// c. 将计算结果写入到reply
reply.writeInt(result);
return true;
}
}
return super.onTransact(code, data, reply, flags);
// 2. 将结算结果返回 到Binder驱动
步骤3:Server
进程 将目标方法的结果(即加法后的结果)返回给Client
进程
// 1. Binder驱动根据 代理对象 沿原路 将结果返回 并通知Client进程获取返回结果
// 2. 通过代理对象 接收结果(之前被挂起的线程被唤醒)
binderproxy.transact(Stub.ADD, data, reply, 0);
reply.readException();;
result = reply.readInt();
}
}