android binder IPC 通信中 asInterface 与 asBinder
Binder 用于通信,Interface用于功能調(diào)用。
其實(shí)asInterface 完成的是Binder到Interface的轉(zhuǎn)換,具體就是:
BBinder->BnInterface
BpBinder->BpInterface
而asBinder功能則相反,具體是:
BnInterface->BBinder
BpInterface->BpBinder
asInterface 與 asBinder 的返回值與輸入?yún)?shù)和調(diào)用對(duì)象有關(guān),如下:
template<typename INTERFACE>
IBinder* BnInterface<INTERFACE>::onAsBinder()
{
return this;
}
template<typename INTERFACE>
inline IBinder* BpInterface<INTERFACE>::onAsBinder()
{
return remote();
}
sp<IXxx>asInterface( const sp<IBinder>& obj)
{
sp<IXxx> intr;
if (obj != NULL) {
intr = static_cast<IXxx*>(obj->queryLocalInterface(descriptor).get());
if (intr == NULL) {
intr = new BpIXxx(obj);
}
}
return intr;
}
1、調(diào)用由 繼承自BnInterface的類 實(shí)例化的對(duì)象,返回對(duì)象本身,因?yàn)楸緛砭驮擃惐緛砭屠^承自 BBinder。
2、調(diào)用由 繼承自BpInterface的類 實(shí)例化的對(duì)象,返回的是BpBinder。
3、調(diào)用asInterface 時(shí),如果傳入的是繼承自BBinder的類 實(shí)例化的對(duì)象,返回的是BnInterface。
4、調(diào)用asInterface 時(shí),如果傳入的是繼承自BpBinder的類 實(shí)例化的對(duì)象,返回的是BpInterface。
======================================================================================
使用情景之一:從 A 服務(wù)中獲取 Xxx 服務(wù),IXxx 繼承自IInterface。
A server 建立BnInterface,A client 獲得 BpInterface,而 BpBinder 和 BBinder 扮演信使的作用。
在 client 端使用某個(gè)功能時(shí),一般用IXxx->Func() 的形式,那么如何得到IXxx呢?
1、通過 A 的 client 向 A 的 server 發(fā)送GET_XXX 命令
IA->remote()->transact(GET_XXX, data, &reply);
其中IA->remote() 返回的 A 的 BpBinder。
2、A 的 server 通過 A 的 BBinder收到GET_XXX 命令
調(diào)用 BnA 的onTransact
status_t BnA::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch(code) {
case GET_XXX: {
CHECK_INTERFACE(IXxx, data, reply);
sp<IXxx> x = createXxx();
reply->writeStrongBinder(x->asBinder());
return NO_ERROR;
} break;
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
createXxx() 返回的是 new 出來的 Xxx 對(duì)象,而 Xxx 在此處代表一個(gè)BnInterface。
3、reply->writeStrongBinder(x->asBinder())
asBinder 在BnInterface 中實(shí)現(xiàn)
template<typename INTERFACE>
IBinder* BnInterface<INTERFACE>::onAsBinder()
{
return this;
}
即返回的是自身,因?yàn)?BnInterface 同時(shí)是一個(gè) BBinder。
reply->writeStrongBinder 調(diào)用 Binder 驅(qū)動(dòng),Binder 驅(qū)動(dòng)將BBinder的引用返回給 client。
4、reply.readStrongBinder()
reply.readStrongBinder() 返回的是BBinder 的代理對(duì)象 BpBinder
return interface_cast<IXxx>(reply.readStrongBinder());
5、interface_cast<IXxx>
interface_cast 展開
template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
return INTERFACE::asInterface(obj);
}
將 BpBinder 轉(zhuǎn)為IXxx,也就是 BpInterface。
至此得到了與 Xxx server 有關(guān)聯(lián)的 IXxx,當(dāng)然,實(shí)際上建立的 BpXxx 與 BnXxx 之間的通信。
總結(jié)
以上是生活随笔為你收集整理的android binder IPC 通信中 asInterface 与 asBinder的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android进出动画有白屏,Andro
- 下一篇: android+rom+bootload