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 之間的通信。