Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 基礎再學習:AIDL 進程間通信完整解析

編輯:關於 Android 程式設計

AIDL 是 Android Interface Definition Language 的縮寫,本質上是一份「跨進程接口的契約」。它解決的是一個很現實的問題:Android 上,一個進程無法直接存取另一個進程的記憶體空間,因此當你要讓 A 應用的客戶端呼叫 B 應用的服務時,必須先把物件拆解成作業系統能理解的原始型態,依序序列化後送過進程邊界,另一端再還原。這段繁瑣又冗長的搬運程式碼,AIDL 幫你自動生成。

什麼時候真的需要 AIDL

先潑一盆冷水:大多數應用都不需要 AIDL。只有同時滿足兩個條件時它才是必要的——你需要讓不同應用的客戶端跨進程存取你的 Service,而且你的 Service 需要處理多執行緒。

  • 不需要跨應用的 IPC 併發 → 直接繼承 Binder 建立本地接口即可。
  • 需要 IPC,但不需要處理多執行緒 → 用 Messenger,它會把請求排隊,省去你自己寫鎖的麻煩。

不論走哪條路,都請先讀懂 Bound Service 再動手。

設計 AIDL 接口前必須理解的執行緒模型

這是最容易被忽略、也最容易釀成 bug 的一點:呼叫 AIDL 接口就是一次普通的函式呼叫,你不能假設它跑在哪一條執行緒上。

  • 本地進程的呼叫:與呼叫者在同一條執行緒執行。若呼叫來自主 UI 執行緒,你的實作就跑在主執行緒上;若來自其他執行緒,就跑在那條執行緒上。也就是說,只有本地存取時你能控制執行緒——但如果是這種情況,你根本該改用 Binder。
  • 遠程進程的呼叫:平台會在你自己的進程內維護一個執行緒池來分配這些呼叫。你必須為「來自未知執行緒、且可能同時有多個」的呼叫做好準備。結論一句話:AIDL 的實作必須是完全的執行緒安全的。
  • oneway 關鍵字:加上它之後,遠程呼叫不會被阻塞,只是把資料送出去就立刻返回;介面的實作會把它當成來自 Binder 執行緒池的普通呼叫來接收。本地呼叫即使宣告 oneway 也不受影響,但依然是同步的。

定義一個 AIDL 接口

AIDL 用 Java 語法撰寫,每個 .aidl 檔案只能定義一個接口,內容僅包含接口宣告與方法簽名。檔案要放在服務端與所有客戶端的 src 目錄下。編譯時,Android SDK 工具會依據它產生 IBinder 接口,存到專案的 gen 目錄。

AIDL 預設支援的型別:

  • Java 全部基本型別(int、long、char、boolean 等)。
  • String、CharSequence
  • List:元素必須是上述型別、其他 AIDL 生成的接口,或你自己定義的 Parcelable。可以使用泛型;接收端實際收到的通常是 ArrayList。
  • Map:限制同上,不支援泛型 Map;接收端實際收到的通常是 HashMap。

除此之外的型別,即使在同一個套件內也必須寫 import。

撰寫時的注意事項:

  • 方法可以帶 0 個或多個參數,並有回傳值或回傳 void。
  • 所有非基本型別的參數都必須標註方向:in(輸入)、out(輸出)、inout(雙向)。基本型別預設支援且不可標註。
  • 方向標註應該限制在真正需要的地方,因為參數的 marshal 與 unmarshal 開銷並不便宜。
  • 介面中的註解會被複製到生成的 IBinder 檔案裡(import 與 package 宣告之前的註解除外)。
  • AIDL 只支援方法,不能暴露靜態欄位。
// IRemoteService.aidl
package com.example.android;

/** Example service interface */
interface IRemoteService {
    /** Request the process ID of this service, to do evil things with it. */
    int getPid();

    /** Demonstrates some basic types that you can use as parameters
     *  and return values in AIDL. */
    void basicTypes(int anInt, long aLong, boolean aBoolean,
                    float aFloat, double aDouble, String aString);
}

存檔後 build 一次,SDK 工具會在 gen 目錄產生檔名相同、副檔名為 .java 的 IBinder 檔案(IRemoteService.aidl → IRemoteService.java)。Eclipse 幾乎是即時生成;用 Ant 的話則在下次 ant debug 或 ant release 時產生。

實現接口

生成的檔案裡有一個名為 Stub 的抽象子類,它繼承 Binder 並宣告了 aidl 中所有方法。你要做的就是繼承 Stub 並實作这些方法。

Stub 還定義了一些輔助方法,最值得注意的是 asInterface():它接收一個 IBinder(通常是 onServiceConnected() 回呼傳來的參數),並回傳 Stub 介面的實例。

private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
    public int getPid() {
        return Process.myPid();
    }
    public void basicTypes(int anInt, long aLong, boolean aBoolean,
                           float aFloat, double aDouble, String aString) {
        // Does nothing
    }
};

實作時的三條鐵律:

  • 呼叫不保證在主執行緒執行,一開始就要把設計做成執行緒安全的。
  • 遠程程序呼叫預設是同步的。若 Service 處理請求會耗時,絕對不要從 Activity 主執行緒直接呼叫,否則容易觸發 ANR;正確做法是在客戶端另開一條執行緒。
  • 拋出的異常不會回傳給呼叫者。

把接口暴露給客戶端

繼承 Service,覆寫 onBind() 並回傳 Stub 實作即可。

public class RemoteService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;      // 把接口交出去
    }

    private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
        public int getPid() {
            return Process.myPid();
        }
        public void basicTypes(int anInt, long aLong, boolean aBoolean,
                               float aFloat, double aDouble, String aString) {
            // Does nothing
        }
    };
}

客戶端呼叫 bindService() 之後,onServiceConnected() 回呼會收到 onBind() 回傳的那個 mBinder。客戶端必須取得介面類別,所以若雙方不在同一個應用,客戶端專案也要有一份 .aidl 副本放在 src 下。收到 IBinder 後,用 Stub.asInterface() 把它轉型:

IRemoteService mIRemoteService;

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        mIRemoteService = IRemoteService.Stub.asInterface(service);
    }

    public void onServiceDisconnected(ComponentName className) {
        Log.e(TAG, "Service has unexpectedly disconnected");
        mIRemoteService = null;
    }
};

跨進程傳遞自訂物件:Parcelable

可以,但有兩個前提:對端也必須有這個類別的程式碼,而且該類別必須實作 Parcelable。Parcelable 的意義在於讓 Android 系統能把物件拆解為可跨進程傳輸的連續基本單位。

要建立一個支援 Parcelable 的類別:

  • 實作 Parcelable 介面。
  • 實作 writeToParcel(),把物件目前的狀態寫進 Parcel。
  • 在類別中新增一個名為 CREATOR 的靜態欄位,實作 Parcelable.Creator。
  • 最後建立一個 .aidl 檔案宣告這個 parcelable 類別。注意:這類 .aidl 檔不會被編譯,作用類似 C 語言的標頭檔。
// Rect.aidl
package android.graphics;

// Declare Rect so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable Rect;
import android.os.Parcel;
import android.os.Parcelable;

public final class Rect implements Parcelable {
    public int left;
    public int top;
    public int right;
    public int bottom;

    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        public Rect createFromParcel(Parcel in) {
            return new Rect(in);
        }
        public Rect[] newArray(int size) {
            return new Rect[size];
        }
    };

    public Rect() { }

    private Rect(Parcel in) {
        readFromParcel(in);
    }

    public void writeToParcel(Parcel out) {
        out.writeInt(left);
        out.writeInt(top);
        out.writeInt(right);
        out.writeInt(bottom);
    }

    public void readFromParcel(Parcel in) {
        left = in.readInt();
        top = in.readInt();
        right = in.readInt();
        bottom = in.readInt();
    }
}

安全性提醒:從其他進程收到的資料一律視為不可信。上面 Rect 從 Parcel 讀進 4 個整數,但你必須自行驗證這些值落在合理範圍內,而不論對方是否刻意構造了惡意內容。

編譯後到底生成了什麼

以一個自訂介面為例:

package com.cao.android.demos.binder.aidl;
import com.cao.android.demos.binder.aidl.AIDLActivity;

interface AIDLService {
    void registerTestCall(AIDLActivity cb);
    void invokCallBack();
}

編譯後會得到三個東西:

  • 介面 AIDLService:繼承 android.os.IInterface,與 aidl 中定義的接口一一對應。
  • Stub 抽象類:繼承 android.os.Binder,在 onTransact() 中接收通信資料,依 code 分派到對應的介面方法,並回寫結果。由服務端實作。
  • Proxy 代理類:實作 AIDLService 介面,但每個方法只做一件事——把呼叫打包成遠程請求。真正的操作在遠端的 Stub 裡執行。由客戶端使用。

這個結構與 axis 依 WSDL 產生 client/server 骨架的思路是一致的:Stub 與 Proxy 把進程通信的細節完全封裝起來,使用者眼中就只是一次普通的介面呼叫。

完整呼叫鏈拆解

1. 服務端實作 Stub,並在 onBind 回傳:

@Override
public IBinder onBind(Intent intent) {
    return mBinder;      // mBinder 為 AIDLService.Stub 的實作
}

2. 客戶端在 onServiceConnected 取得 IBinder:

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        mService = AIDLService.Stub.asInterface(service);
        try {
            mService.registerTestCall(mCallback);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
};
// 別忘了把它傳進去
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

3. asInterface() 的關鍵分支:

public static AIDLService asInterface(android.os.IBinder obj) {
    if (obj == null) {
        return null;
    }
    android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
    // 若綁定的是同進程 Service,直接回傳 Stub 本身,根本不進程通信
    if (iin != null && iin instanceof AIDLService) {
        return (AIDLService) iin;
    }
    // 否則回傳 Proxy 包裝 BinderProxy
    return new AIDLService.Stub.Proxy(obj);
}

這段程式說明了一件很重要的事:AIDL 在跨進程時才真的走 IPC,同進程時會自動退化成本地直接呼叫。

4. Proxy 方法的實作:

public void invokCallBack() throws android.os.RemoteException {
    android.os.Parcel _data = android.os.Parcel.obtain();
    android.os.Parcel _reply = android.os.Parcel.obtain();
    try {
        // DESCRIPTOR 描述要呼叫哪個 Stub 物件
        _data.writeInterfaceToken(DESCRIPTOR);
        // TRANSACTION_invokCallBack 標識要呼叫 Stub 中的哪個方法
        // mRemote 即 BinderProxy,負責跨進程搬運資料
        mRemote.transact(Stub.TRANSACTION_invokCallBack, _data, _reply, 0);
        _reply.readException();
    } finally {
        _reply.recycle();
        _data.recycle();
    }
}

5. 進入 native 層:

public native boolean transact(int code, Parcel data, Parcel reply, int flags)
        throws RemoteException;
// 對應 JNI:/frameworks/base/core/jni/android_util_Binder.cpp
// → static jboolean android_os_BinderProxy_transact(...)

6. 服務端接收,呼叫堆疊:

AIDLService.Stub.onTransact
AIDLService.Stub(Binder).execTransact
NativeStart.run
public boolean onTransact(int code, android.os.Parcel data,
                           android.os.Parcel reply, int flags)
        throws android.os.RemoteException {
    switch (code) {
        case INTERFACE_TRANSACTION:
            reply.writeString(DESCRIPTOR);
            return true;

        case TRANSACTION_registerTestCall:
            data.enforceInterface(DESCRIPTOR);
            AIDLActivity _arg0 = AIDLActivity.Stub.asInterface(data.readStrongBinder());
            this.registerTestCall(_arg0);
            reply.writeNoException();
            return true;

        case TRANSACTION_invokCallBack:
            data.enforceInterface(DESCRIPTOR);
            this.invokCallBack();     // 由服務端的 Stub 子類實作
            reply.writeNoException();
            return true;
    }
    return super.onTransact(code, data, reply, flags);
}

呼叫端的標準八步

  1. 在專案 src 目錄放入 .aidl 檔。
  2. 宣告一個 IBinder 介面的實例。
  3. 實作 ServiceConnection。
  4. 呼叫 Context.bindService(),傳入 ServiceConnection。
  5. 在 onServiceConnected() 中取得 IBinder。
  6. 呼叫 YourInterface.Stub.asInterface(service) 完成轉型。
  7. 呼叫介面中定義的方法,並捕捉 DeadObjectException——這是遠程方法唯一會拋出的異常。
  8. 用完呼叫 Context.unbindService() 解除連線。

另外記得:跨進程傳遞的物件是引用計數的,而你可以把匿名物件當作方法參數傳過去。

研究到這裡的結論

AIDL 的表層是「寫一個介面描述檔,工具幫你生成 Java 骨架」,底層則是 Binder 驅動 + JNI + native 的 Parcel 搬運。理解 Stub / Proxy 的分工、asInterface 的同進程捷徑、以及 onTransact 的 code 分派,就足以應付九成的Framework 閱讀需求;再往下的 C++ 層如何完成實際的進程通信,則是另一個主題了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved