BpBinder 转换为 BpCameraService 流程

本文解析了Android中Binder机制的使用方式,通过ICameraService接口的具体实例,详细阐述了如何利用interface_cast创建BpCameraService对象的过程及其内部实现原理。
interface_cast<ICameraService>(binder)    : 其中binder 为IBinder类型,实际为BpBinder

interface_cast 定义在IInterface.h文件中,如下:

声明如下:

#define DECLARE_META_INTERFACE(INTERFACE) \
static const android::String16 descriptor; \
static android::sp<I##INTERFACE> asInterface( \
const android::sp<android::IBinder>& obj); \
virtual const android::String16& getInterfaceDescriptor() const; \
I##INTERFACE(); \
virtual ~I##INTERFACE(); \

 

定义如下:

#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME) \

android::sp<I##INTERFACE> I##INTERFACE::asInterface( \
const android::sp<android::IBinder>& obj) \
{ \
android::sp<I##INTERFACE> intr; \
if (obj != NULL) { \
intr = static_cast<I##INTERFACE*>( \
obj->queryLocalInterface( \
I##INTERFACE::descriptor).get()); \
if (intr == NULL) { \
intr = new Bp##INTERFACE(obj); \
} \
} \
return intr; \
} \


见代码:intr = new Bp##INTERFACE(obj), 这里INTERFACE为ICameraService, 即new BpCameraService(obj);

frameworks/av/camera/ICameraService.h 中BpCameraService的定义

BpCameraService(const sp<IBinder>& impl)
: BpInterface<ICameraService>(impl)
{
}

 

BpInterface(impl), 将BpBinder传递给了BpInterface, 再看:

frameworks/native/include/IInterface.h 中BpInterface的实现(这里实现也放在头文件了)

template<typename INTERFACE>
inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)
: BpRefBase(remote)
{
}

BpRefBase(remote),将BpBinder 又传递给了BpRefBase中,继续跟进

frameworks/native/libs/binder/Binder.cpp 中看BpRefBase的实现

BpRefBase::BpRefBase(const sp<IBinder>& o)
: mRemote(o.get()), mRefs(NULL), mState(0)
{
extendObjectLifetime(OBJECT_LIFETIME_WEAK);

if (mRemote) {
mRemote->incStrong(this); // Removed on first IncStrong().
mRefs = mRemote->createWeak(this); // Held for our entire lifetime.
}
}

mRemote(o.get()), 这里将BpBinder 保存在了BpRefBase中的变量mRemote中

 

又有BpCameraService 继承 BpInterface 继承 BpRefBase 继承 RefBase,所以 interface_cast 实际上是创建了一个BpCameraService对象,并且将BpBinder复制给它的祖先类


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值