Binder上层原理浅析
1. IBinder简介
Binder实现IBinder接口,IBinder是一个接口,代表一种跨进程传输的能力,实现此接口,就可以将此对象进行跨进程传递。
根据IBinder的源码介绍及分析,可以了解很多信息(译自IBinder的源码介绍并总结):
1. IBinder是高性能、轻量级进程间通信的基本接口,该接口定义了与远程对象通信的协议。不能直接实现此接口,而要继承自它的实现类Binder。
2. IBinder主要API是transact()和Binder的onTransact(), 这两个方法进行发送和接收Binder对象,调用trasact的返回数据会在onTransact回调后返回。
场景:调用IBinder的transact()给IBinder对象发送请求,然后经过Binder的Binder.onTransact()得到调用,远程操作的目标得到回调。
IBinder的transact方法:
/**
* Perform a generic operation with the object.
*
* @param code The action to perform. This should
* be a number between {@link #FIRST_CALL_TRANSACTION} and
* {@link #LAST_CALL_TRANSACTION}.
* @param data Marshalled data to send to the target. Must not be null.
* If you are not sending any data, you must create an empty Parcel
* that is given here.
* @param reply Marshalled data to be received from the target. May be
* null if you are not interested in the return value.
* @param flags Additional operation flags. Either 0 for a normal
* RPC, or {@link #FLAG_ONEWAY} for a one-way RPC.
*/
public boolean transact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException;
与他对应的Binder的onTransact方法:
/**
* Default implementation is a stub that returns false. You will want
* to override this to do the appropriate unmarshalling of transactions.
*
* <p>If you want to call this, call transact().
*/
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {}
两个方法的参数一致,参数具体意义是什么?
- code:要执行的动作,类似于Handler的what,自定义Code值需要在
IBinder.FIRST_CALL_TRANSACTION(0x00000001)和IBinder.LAST_CALL_TRANSACTION(0x00ffffff)之间。其中IBinder内部定义了部分code:
- PING_TRANSACTION:表示要调用
pingBinder() - DUMP_TRANSACTION:获取Binder内部状态
- SHELL_COMMAND_TRANSACTION:执行一个Shell命令
- INTERFACE_TRANSACTION:询问接收方的接口描述符号
- TWEET_TRANSACTION:发送推文给目标对象
- LIKE_TRANSACTION
- PING_TRANSACTION:表示要调用
- <

本文深入浅出地解析了Android中Binder的上层原理,包括IBinder接口的介绍,Binder的transact()和onTransact()方法的工作机制,以及进程间通信的关键点。通过分析,展示了Binder如何实现跨进程通信,以及在通信过程中如何处理线程调度、错误检测和递归调用。同时,文中还提及了AIDL自动生成的接口代码,强调了Stub和Proxy类在Binder通信中的核心作用。
最低0.47元/天 解锁文章
3486

被折叠的 条评论
为什么被折叠?



