0%

Android FrameWork - Binder framework层分析

Binder架构

binder在framework层,采用JNI技术来调用native(C/C++)层的binder架构,从而为上层应用程序提供服务。 在native层中,binder是C/S架构,分为Bn端(Server)和Bp端(Client)。对于java层在命名与架构上非常相近,同样实现了一套IPC通信架构。

framework Binder架构图:

avatar

framework Binder初始化流程图UML:

avatar

framework Binder注册服务和获取服务流程图UML:

avatar

总结

addService的核心过程:

1
2
3
4
5
6
7
public void addService(String name, IBinder service, boolean allowIsolated) throws RemoteException {
...
Parcel data = Parcel.obtain(); //此处还需要将java层的Parcel转为Native层的Parcel
data->writeStrongBinder(new JavaBBinder(env, obj));
BpBinder::transact(ADD_SERVICE_TRANSACTION, *data, reply, 0); //与Binder驱动交互
...
}

注册服务过程就是通过BpBinder来发送ADD_SERVICE_TRANSACTION命令,与实现与binder驱动进行数据交互。

getService的核心过程:

1
2
3
4
5
6
7
public static IBinder getService(String name) {
...
Parcel reply = Parcel.obtain(); //此处还需要将java层的Parcel转为Native层的Parcel
BpBinder::transact(GET_SERVICE_TRANSACTION, *data, reply, 0); //与Binder驱动交互
IBinder binder = javaObjectForIBinder(env, new BpBinder(handle));
...
}

javaObjectForIBinder作用是创建BinderProxy对象,并将BpBinder对象的地址保存到BinderProxy对象的mObjects中。 获取服务过程就是通过BpBinder来发送GET_SERVICE_TRANSACTION命令,与实现与binder驱动进行数据交互。