Android 淺析 Binder機(jī)制 基礎(chǔ)(一)

Android Binder機(jī)制 基礎(chǔ)(一)


前言

Linus Benedict Torvalds : RTFSC – Read The Fucking Source Code

Dianne Hackborn 記住這家伙,這系統(tǒng)他做的。

Binder 簡(jiǎn)要

Binder:用來實(shí)現(xiàn)不用進(jìn)程間通信。Binder屬于一個(gè)驅(qū)動(dòng),工作在linux層,運(yùn)行在kernel。服務(wù)端,客戶端處在用戶空間,binder驅(qū)動(dòng)處在內(nèi)核空間。


binder

Binder機(jī)制有兩個(gè)重要的類:IBinder和Binder。通過分析這兩個(gè)主要的類來淺析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.
翻譯:
一個(gè)遠(yuǎn)程對(duì)象的基本接口,一個(gè)輕量級(jí)的遠(yuǎn)程程序的調(diào)用機(jī)制的核心部分專為高性能設(shè)計(jì)在執(zhí)行程序和跨進(jìn)程調(diào)用。該接口描述了與遠(yuǎn)程對(duì)象交互的抽象協(xié)議。注意:不要直接實(shí)現(xiàn)這個(gè)接口,而不是從“Binder”中擴(kuò)展。

IBinder的核心API是transact transact()匹配在Binder類的onTransact Binder.onTransact()函數(shù)中。這方法允許你發(fā)送一個(gè)調(diào)用到一個(gè)IBinder對(duì)象和從IBinder對(duì)象中收到一個(gè)調(diào)用。這個(gè)API是同步的。

通過transact()傳輸?shù)臄?shù)據(jù)是一個(gè)Parcel,一個(gè)通用的緩存數(shù)據(jù),同時(shí)也有一些元數(shù)據(jù)。在buffer中元數(shù)據(jù)使用來管理IBinder對(duì)象標(biāo)記的,這樣的引用可以在buffer穿越過程中得以保留。這種機(jī)制確保IBinder被寫入Parcel發(fā)送到另一個(gè)進(jìn)程,如果其他進(jìn)程發(fā)送一個(gè)標(biāo)記到同一個(gè)IBinder回到原來的過程,那么原始的過程中會(huì)接收到同一個(gè)IBinder對(duì)象回來。這些語義允許IBinder/Binder對(duì)象作為一個(gè)獨(dú)特的身份(作為一個(gè)記號(hào)或作其他用途),可以在過程管理。

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ā)送一個(gè)消息到一個(gè)Binder對(duì)象和接收一個(gè)從Binder對(duì)象發(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)程對(duì)象是否有效有三個(gè)方法:
    • The transact(); 如果對(duì)象被銷毀而你嘗試去調(diào)用這個(gè)函數(shù),它會(huì)拋出一個(gè)異常。
    • The pingBinder(); 如果對(duì)象被銷毀,它會(huì)返回false。
    • The linkToDeath(); 用來注冊(cè)一個(gè)DeathRecipient,當(dāng)被銷毀的時(shí)候?qū)?huì)監(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)程對(duì)象,由定義的IBinder一個(gè)輕量級(jí)的遠(yuǎn)程過程調(diào)用機(jī)制的核心組成部分。這個(gè)類是的IBinder的實(shí)現(xiàn),提供了標(biāo)準(zhǔn)的地方實(shí)現(xiàn)這樣一個(gè)目標(biāo)的。

大多數(shù)開發(fā)者不應(yīng)該直接實(shí)現(xiàn)這個(gè)類,作為代替應(yīng)該使用AIDl工具去描述你想要的接口,產(chǎn)生合適的Binder子類。但是,你可以直接使用Binder來實(shí)現(xiàn)自定義的RPC協(xié)議或簡(jiǎn)單地實(shí)例化一個(gè)Binder的對(duì)象來直接使用作為一個(gè)記號(hào)可以共享的過程。

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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,197評(píng)論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,415評(píng)論 3 415
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,104評(píng)論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,884評(píng)論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,647評(píng)論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,130評(píng)論 1 323
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,208評(píng)論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,366評(píng)論 0 288
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,887評(píng)論 1 334
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,737評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,939評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,478評(píng)論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,174評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,586評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,827評(píng)論 1 283
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,608評(píng)論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,914評(píng)論 2 372

推薦閱讀更多精彩內(nèi)容