Android Binder機制 基礎(chǔ)(一)
前言
Linus Benedict Torvalds : RTFSC – Read The Fucking Source Code
Dianne Hackborn 記住這家伙,這系統(tǒng)他做的。
Binder 簡要
Binder:用來實現(xiàn)不用進程間通信。Binder屬于一個驅(qū)動,工作在linux層,運行在kernel。服務(wù)端,客戶端處在用戶空間,binder驅(qū)動處在內(nèi)核空間。

Binder機制有兩個重要的類:IBinder和Binder。通過分析這兩個主要的類來淺析Binder的使用。
1、IBinder
Base interface for a remotable object, the core part of a lightweight remote procedure call mechanism designed for high performance when performing in-process and cross-process calls. This interface describes the abstract protocol for interacting with a remotable object. Do not implement this interface directly, instead extend from Binder.
翻譯:
一個遠(yuǎn)程對象的基本接口,一個輕量級的遠(yuǎn)程程序的調(diào)用機制的核心部分專為高性能設(shè)計在執(zhí)行程序和跨進程調(diào)用。該接口描述了與遠(yuǎn)程對象交互的抽象協(xié)議。注意:不要直接實現(xiàn)這個接口,而不是從“Binder”中擴展。
IBinder的核心API是transact transact()匹配在Binder類的onTransact Binder.onTransact()函數(shù)中。這方法允許你發(fā)送一個調(diào)用到一個IBinder對象和從IBinder對象中收到一個調(diào)用。這個API是同步的。
通過transact()傳輸?shù)臄?shù)據(jù)是一個Parcel,一個通用的緩存數(shù)據(jù),同時也有一些元數(shù)據(jù)。在buffer中元數(shù)據(jù)使用來管理IBinder對象標(biāo)記的,這樣的引用可以在buffer穿越過程中得以保留。這種機制確保IBinder被寫入Parcel發(fā)送到另一個進程,如果其他進程發(fā)送一個標(biāo)記到同一個IBinder回到原來的過程,那么原始的過程中會接收到同一個IBinder對象回來。這些語義允許IBinder/Binder對象作為一個獨特的身份(作為一個記號或作其他用途),可以在過程管理。
The system maintains a pool of transaction threads in each process that it runs in. These threads are used to dispatch all IPCs coming in from other processes.
The Binder system also supports recursion across processes.
1.1、transact()方法
- IBinder核心接口方法:
- 允許你可以分別發(fā)送一個消息到一個Binder對象和接收一個從Binder對象發(fā)出的消息。
/*
Perform a generic operation with the object.
@param code The action to perform. This should be a number between FIRST_CALL_TRANSACTION and 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 FLAG_ONEWAY for a one-way RPC.
*/
public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException;
- 確認(rèn)遠(yuǎn)程對象是否有效有三個方法:
- The transact(); 如果對象被銷毀而你嘗試去調(diào)用這個函數(shù),它會拋出一個異常。
- The pingBinder(); 如果對象被銷毀,它會返回false。
- The linkToDeath(); 用來注冊一個DeathRecipient,當(dāng)被銷毀的時候?qū)O(jiān)聽到。
2、Binder
Base class for a remotable object, the core part of a lightweight remote procedure call mechanism defined by IBinder. This class is an implementation of IBinder that provides standard local implementation of such an object.
翻譯:
基類可遠(yuǎn)程對象,由定義的IBinder一個輕量級的遠(yuǎn)程過程調(diào)用機制的核心組成部分。這個類是的IBinder的實現(xiàn),提供了標(biāo)準(zhǔn)的地方實現(xiàn)這樣一個目標(biāo)的。
大多數(shù)開發(fā)者不應(yīng)該直接實現(xiàn)這個類,作為代替應(yīng)該使用AIDl工具去描述你想要的接口,產(chǎn)生合適的Binder子類。但是,你可以直接使用Binder來實現(xiàn)自定義的RPC協(xié)議或簡單地實例化一個Binder的對象來直接使用作為一個記號可以共享的過程。
2.1、transact()方法
/**Default implementation rewinds the parcels and calls onTransact. On the remote side, transact calls into the binder to do the IPC.*/
public final boolean transact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
if (false) Log.v("Binder", "Transact: " + code + " to " + this);
if (data != null) {
data.setDataPosition(0);
}
boolean r = onTransact(code, data, reply, flags);
if (reply != null) {
reply.setDataPosition(0);
}
return r;
}
2.2、onTransact()方法
/*Default implementation is a stub that returns false. You will want to override this to do the appropriate unmarshalling of transactions. If you want to call this, call transact().*/
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
if (code == INTERFACE_TRANSACTION) {
...
return true;
} else if (code == DUMP_TRANSACTION) {
...
return true;
}
return false;
}
2.3、execTransact()方法
// Entry point from android_util_Binder.cpp's onTransact
private boolean execTransact(int code, long dataObj, long replyObj,
int flags) {
Parcel data = Parcel.obtain(dataObj);
Parcel reply = Parcel.obtain(replyObj);
// theoretically, we should call transact, which will call onTransact,
// but all that does is rewind it, and we just got these from an IPC,
// so we'll just call it directly.
boolean res;
// Log any exceptions as warnings, don't silently suppress them.
// If the call was FLAG_ONEWAY then these exceptions disappear into the ether.
try {
res = onTransact(code, data, reply, flags);
} catch (RemoteException e) {
if ((flags & FLAG_ONEWAY) != 0) {
} else {
reply.setDataPosition(0);
reply.writeException(e);
}
res = true;
} catch (RuntimeException e) {
if ((flags & FLAG_ONEWAY) != 0) {
} else {
reply.setDataPosition(0);
reply.writeException(e);
}
res = true;
} catch (OutOfMemoryError e) {
// Unconditionally log this, since this is generally unrecoverable.
RuntimeException re = new RuntimeException("Out of memory", e);
reply.setDataPosition(0);
reply.writeException(re);
res = true;
}
checkParcel(this, code, reply, "Unreasonably large binder reply buffer");
reply.recycle();
data.recycle();
// Just in case -- we are done with the IPC, so there should be no more strict
// mode violations that have gathered for this thread. Either they have been
// parceled and are now in transport off to the caller, or we are returning back
// to the main transaction loop to wait for another incoming transaction. Either
// way, strict mode begone!
StrictMode.clearGatheredViolations();
return res;
}