android binder IPC 通信中 asInterface 与 asBinder
Binder 用于通信,Interface用于功能調用。
其實asInterface 完成的是Binder到Interface的轉換,具體就是:
BBinder->BnInterface
BpBinder->BpInterface
而asBinder功能則相反,具體是:
BnInterface->BBinder
BpInterface->BpBinder
asInterface 與 asBinder 的返回值與輸入參數和調用對象有關,如下:
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、調用由 繼承自BnInterface的類 實例化的對象,返回對象本身,因為本來就該類本來就繼承自 BBinder。
2、調用由 繼承自BpInterface的類 實例化的對象,返回的是BpBinder。
3、調用asInterface 時,如果傳入的是繼承自BBinder的類 實例化的對象,返回的是BnInterface。
4、調用asInterface 時,如果傳入的是繼承自BpBinder的類 實例化的對象,返回的是BpInterface。
======================================================================================
使用情景之一:從 A 服務中獲取 Xxx 服務,IXxx 繼承自IInterface。
A server 建立BnInterface,A client 獲得 BpInterface,而 BpBinder 和 BBinder 扮演信使的作用。
在 client 端使用某個功能時,一般用IXxx->Func() 的形式,那么如何得到IXxx呢?
1、通過 A 的 client 向 A 的 server 發送GET_XXX 命令
IA->remote()->transact(GET_XXX, data, &reply);
其中IA->remote() 返回的 A 的 BpBinder。
2、A 的 server 通過 A 的 BBinder收到GET_XXX 命令
調用 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 對象,而 Xxx 在此處代表一個BnInterface。
3、reply->writeStrongBinder(x->asBinder())
asBinder 在BnInterface 中實現
template<typename INTERFACE>
IBinder* BnInterface<INTERFACE>::onAsBinder()
{
return this;
}
即返回的是自身,因為 BnInterface 同時是一個 BBinder。
reply->writeStrongBinder 調用 Binder 驅動,Binder 驅動將BBinder的引用返回給 client。
4、reply.readStrongBinder()
reply.readStrongBinder() 返回的是BBinder 的代理對象 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 轉為IXxx,也就是 BpInterface。
至此得到了與 Xxx server 有關聯的 IXxx,當然,實際上建立的 BpXxx 與 BnXxx 之間的通信。
總結
以上是生活随笔為你收集整理的android binder IPC 通信中 asInterface 与 asBinder的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android进出动画有白屏,Andro
- 下一篇: 通过注册表修改IE的Internet选项