Android 介面定義語言 (AIDL)

Android 介面定義語言 (AIDL) 與其他 IDL 類似:可讓您定義用戶端和服務同意的程式設計介面,以便使用處理序間通訊 (IPC) 相互通訊。

在 Android 上,一個程序通常無法存取另一個程序的記憶體。如要進行通訊,他們必須將物件分解為作業系統可理解的原語,並為您跨越該邊界封送物件。編寫封送處理的程式碼相當繁瑣,因此 Android 會透過 AIDL 為您處理。

注意:只有在您允許來自不同應用程式的用戶端存取您的服務以進行 IPC,且您想要在服務中處理多執行緒時,才需要使用 AIDL。如果不需要在不同應用程式之間執行並行 IPC,請實作 Binder 來建立介面。如果您想執行 IPC,但「不」需要處理多執行緒,請使用 Messenger 實作介面。無論如何,請務必先瞭解繫結服務,再實作 AIDL。

開始設計 AIDL 介面前,請注意,對 AIDL 介面的呼叫是直接函式呼叫。請勿對發生呼叫的執行緒做出假設。視呼叫是來自本機程序中的執行緒還是遠端程序,會發生不同的情況:

  • 從本機程序發出的呼叫會在發出呼叫的同一個執行緒中執行。如果這是您的主要 UI 執行緒,該執行緒會繼續在 AIDL 介面中執行。如果是其他執行緒,則會在服務中執行程式碼。因此,如果只有本機執行緒存取服務,您就能完全控制在服務中執行的執行緒。但如果是這種情況,請完全不要使用 AIDL,而是實作 Binder 來建立介面。
  • 來自遠端程序的呼叫會從平台在您自己的程序中維護的執行緒集區中分派。請做好準備,因應來自不明執行緒的來電,且可能同時有多通來電。換句話說,AIDL 介面的實作必須完全符合執行緒安全。從同一個遠端物件上的某個執行緒發出的呼叫,會依序到達接收端。
  • oneway 關鍵字會修改遠端呼叫的行為。使用時,遠端呼叫不會遭到封鎖。傳送交易資料後,系統會立即傳回。介面的實作最終會收到這項呼叫,做為 Binder 執行緒集區的一般呼叫,做為一般遠端呼叫。如果 oneway 與本機呼叫搭配使用,則不會造成任何影響,且呼叫仍會同步。

定義 AIDL 介面

使用 Java 程式設計語言語法,在 .aidl 檔案中定義 AIDL 介面,然後將其儲存在託管服務的應用程式和繫結至服務的任何其他應用程式的原始碼中,位於 src/ 目錄。

建構每個包含 .aidl 檔案的應用程式時,Android SDK 工具會根據 .aidl 檔案產生 IBinder 介面,並儲存在專案的 gen/ 目錄中。服務必須視情況實作 IBinder 介面。接著,用戶端應用程式可以繫結至服務,並從 IBinder 呼叫方法來執行 IPC。

如要使用 AIDL 建立繫結服務,請按照下列步驟操作 (將於後續章節詳細說明):

  1. 建立 .aidl 檔案

    這個檔案會定義程式設計介面和方法簽章。

  2. 實作介面

    Android SDK 工具會根據 .aidl 檔案,產生 Java 程式設計語言介面。這個介面有一個名為 Stub 的內部抽象類別,可擴充 Binder 並實作 AIDL 介面的方法。您必須擴充 Stub 類別並實作方法。

  3. 向用戶端公開介面

    實作 Service 並覆寫 onBind(),傳回 Stub 類別的實作。

注意:首次發布後,您對 AIDL 介面所做的任何變更都必須保持回溯相容性,以免破壞使用您服務的其他應用程式。也就是說,由於 .aidl 檔案必須複製到其他應用程式,才能存取服務介面,因此您必須繼續支援原始介面。

建立 .aidl 檔案

AIDL 使用簡單的語法,可讓您宣告具有一或多個方法的介面,這些方法可接受參數和傳回值。參數和傳回值可以是任何類型,甚至是其他 AIDL 產生的介面。

您必須使用 Java 程式設計語言建構 .aidl 檔案。每個 .aidl 檔案都必須定義單一介面,且只需要介面宣告和方法簽章。

根據預設,AIDL 支援下列資料類型:

  • Java 程式設計語言中除了 short 以外的所有原始類型 (例如 int、long、char、boolean 等)
  • 任何類型的陣列,例如 int[] 或 MyParcelable[]
  • String
  • CharSequence
  • List

    List 中的所有元素都必須是這份清單中支援的資料類型之一,或是您宣告的其他 AIDL 產生的介面或 Parcelable 之一。List 可選擇做為參數化類型類別,例如 List<String>。雖然系統會產生方法來使用 List 介面,但另一端收到的實際具體類別一律為 ArrayList。

  • Map

    Map 中的所有元素都必須是這份清單中支援的資料類型之一,或是您宣告的其他 AIDL 產生的介面或 Parcelable 之一。不支援參數化類型對應,例如 Map<String,Integer> 形式。雖然系統會產生方法來使用 Map 介面,但另一端收到的實際具體類別一律為 HashMap。建議使用 Bundle 做為 Map 的替代方案。

對於先前未列出的每個額外類型,您都必須加入 import 陳述式,即使這些類型與介面定義在同一個套件中也一樣。

定義服務介面時,請注意下列事項:

  • 方法可以採用零或多個參數,並傳回值或 void。
  • 所有非原始參數都需要方向標記,指出資料的方向:in、out 或 inout (請參閱下方範例)。

    原始物件、String、IBinder 和 AIDL 產生的介面預設為 in,且無法變更。

    注意:請將方向限制在真正需要的範圍內,因為封送處理參數的成本很高。

  • .aidl 檔案中包含的所有程式碼註解都會包含在產生的 IBinder 介面中,但匯入和套件陳述式之前的註解除外。
  • 字串和 int 常數可以在 AIDL 介面中定義,例如 const int VERSION = 1;。
  • 方法呼叫是由 transact() 程式碼分派,通常是以介面中的方法索引為基礎。由於這會導致版本管理困難,因此您可以手動將交易代碼指派給方法:void method() = 10;。
  • 可為空值的引數和傳回類型必須使用 @nullable 加上註解。

以下是 .aidl 檔案範例:

// IRemoteService.aidl
package com.example.android;

// Declare any non-default types here with import statements.

/** Example service interface. */
interface IRemoteService {
    /** Request the process ID of this service. */
    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);
}

將 .aidl 檔案儲存在專案的 src/ 目錄中。 建構應用程式時,SDK 工具會在 專案的 gen/ 目錄中產生 IBinder 介面檔案。產生的檔案名稱與 .aidl 檔案名稱相符,但副檔名為 .java。例如,IRemoteService.aidl 會產生 IRemoteService.java。

如果您使用 Android Studio,遞增建構作業幾乎會立即產生繫結器類別。如果您不使用 Android Studio,Gradle 工具會在您下次建構應用程式時產生繫結器類別。編寫完 .aidl 檔案後,請立即使用 gradle assembleDebug 或 gradle assembleRelease 建構專案,讓程式碼連結至產生的類別。

實作介面

建構應用程式時,Android SDK 工具會產生 .java 介面檔案,並以 .aidl 檔案命名。產生的介面包含名為 Stub 的子類別,這是其父項介面 (例如 YourInterface.Stub) 的抽象實作,並宣告 .aidl 檔案中的所有方法。

注意:Stub 也定義了一些輔助方法,其中最值得注意的是 asInterface(),它會採用 IBinder (通常是傳遞至用戶端 onServiceConnected() 回呼方法的方法),並傳回虛設常式介面的執行個體。如要進一步瞭解如何進行這項轉換,請參閱「呼叫 IPC 方法」一節。

如要實作從 .aidl 產生的介面,請擴充產生的 Binder 介面 (例如 YourInterface.Stub),並實作從 .aidl 檔案繼承的方法。

以下範例說明如何使用匿名例項,實作由上述 IRemoteService.aidl 範例定義的 IRemoteService 介面:

private val binder = object : IRemoteService.Stub() {

    override fun getPid(): Int =
        Process.myPid()

    override fun basicTypes(
        anInt: Int,
        aLong: Long,
        aBoolean: Boolean,
        aFloat: Float,
        aDouble: Double,
        aString: String
    ) {
        // Does nothing.
    }
}

現在,binder 是 Stub 類別 (Binder) 的例項,可定義服務的 IPC 介面。在下一個步驟中,這個執行個體會公開給用戶端,以便與服務互動。

導入 AIDL 介面時,請留意下列幾項規則:

  • 傳入呼叫不一定會在主執行緒上執行,因此您必須從一開始就考慮多執行緒,並妥善建構服務,確保執行緒安全。
  • 根據預設,IPC 呼叫是同步的。如果您知道服務需要超過幾毫秒的時間才能完成要求,請勿從活動的主執行緒呼叫該服務。這可能會導致應用程式停止運作,進而使 Android 顯示「應用程式無回應」對話方塊。從用戶端的獨立執行緒呼叫。
  • 只有 Parcel.writeException() 參考文件中列出的例外狀況類型,才會傳回給呼叫端。

向用戶端公開介面

為服務實作介面後,您需要向用戶端公開介面,以便用戶端繫結至介面。如要公開服務介面,請擴充 Service 並實作 onBind(),以傳回實作所產生 Stub 的類別例項,如上一節所述。以下範例服務會向用戶端公開 IRemoteService 範例介面。

class RemoteService : Service() {

    override fun onCreate() {
        super.onCreate()
    }

    override fun onBind(intent: Intent): IBinder {
        // Return the interface.
        return binder
    }

    private val binder = object : IRemoteService.Stub() {
        override fun getPid(): Int {
            return Process.myPid()
        }

        override fun basicTypes(
            anInt: Int,
            aLong: Long,
            aBoolean: Boolean,
            aFloat: Float,
            aDouble: Double,
            aString: String
        ) {
            // Does nothing.
        }
    }
}

現在,當用戶端 (例如活動) 呼叫 bindService() 連線至這項服務時,用戶端的 onServiceConnected() 回呼會收到服務 onBind() 方法傳回的 binder 執行個體。

用戶端也必須具備介面類別的存取權。因此,如果用戶端和服務位於不同的應用程式,用戶端的應用程式必須在 src/ 目錄中包含 .aidl 檔案的副本,以便產生 android.os.Binder 介面,讓用戶端存取 AIDL 方法。

用戶端在 onServiceConnected() 回呼中收到 IBinder 時,必須呼叫 YourServiceInterface.Stub.asInterface(service),將傳回的參數轉換為 YourServiceInterface 類型:

var iRemoteService: IRemoteService? = null

val mConnection = object : ServiceConnection {

    // Called when the connection with the service is established.
    override fun onServiceConnected(className: ComponentName, service: IBinder) {
        // Following the preceding example for an AIDL interface,
        // this gets an instance of the IRemoteInterface, which we can use to call on the service.
        iRemoteService = IRemoteService.Stub.asInterface(service)
    }

    // Called when the connection with the service disconnects unexpectedly.
    override fun onServiceDisconnected(className: ComponentName) {
        Log.e(TAG, "Service has unexpectedly disconnected")
        iRemoteService = null
    }
}

如需更多程式碼範例,請參閱 ApiDemos 中的 RemoteService.java 類別。

透過 IPC 傳遞物件

在 Android 10 (API 級別 29 以上) 中,您可以直接在 AIDL 中定義 Parcelable 物件。這裡也支援 AIDL 介面引數和其他 Parcelable 支援的類型。這樣就不必手動編寫封送處理程式碼和自訂類別。不過,這也會建立裸結構。如需自訂存取子或其他功能,請改為實作 Parcelable。

package android.graphics;

// Declare Rect so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable Rect {
    int left;
    int top;
    int right;
    int bottom;
}

上述程式碼範例會自動產生具有整數欄位 left、top、right 和 bottom 的 Java 類別。系統會自動實作所有相關的封送處理程式碼,且物件可直接使用,無須新增任何實作。

您也可以透過 IPC 介面,將自訂類別從一個程序傳送至另一個程序。不過,請務必確保 IPC 管道的另一端可使用類別的程式碼,且類別必須支援 Parcelable 介面。支援 Parcelable 很重要,因為這可讓 Android 系統將物件分解為可跨程序封送處理的基本物件。

如要建立支援 Parcelable 的自訂類別,請按照下列步驟操作:

  1. 讓類別實作 Parcelable 介面。
  2. 實作 writeToParcel,這會擷取物件的目前狀態,並寫入 Parcel。
  3. 在類別中新增名為 CREATOR 的靜態欄位,該欄位是實作 Parcelable.Creator 介面的物件。
  4. 最後,建立宣告 Parcelable 類別的 .aidl 檔案,如下列 Rect.aidl 檔案所示。

    如果您使用自訂建構程序,請勿將 .aidl 檔案新增至建構作業。與 C 語言中的標頭檔案類似,這個 .aidl 檔案不會經過編譯。

AIDL 會在產生的程式碼中使用這些方法和欄位,封送處理及取消封送處理物件。

舉例來說,以下 Rect.aidl 檔案會建立可封裝的 Rect 類別:

package android.graphics;

// Declare Rect so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable Rect;

以下範例說明 Rect 類別如何實作 Parcelable 協定。

// import android.os.Parcel
// import android.os.Parcelable

class Rect() : Parcelable {
    var left: Int = 0
    var top: Int = 0
    var right: Int = 0
    var bottom: Int = 0

    companion object CREATOR : Parcelable.Creator<Rect> {
        override fun createFromParcel(parcel: Parcel): Rect {
            return Rect(parcel)
        }

        override fun newArray(size: Int): Array<Rect?> {
            return Array(size) { null }
        }
    }

    private constructor(inParcel: Parcel) : this() {
        readFromParcel(inParcel)
    }

    override fun writeToParcel(outParcel: Parcel, flags: Int) {
        outParcel.writeInt(left)
        outParcel.writeInt(top)
        outParcel.writeInt(right)
        outParcel.writeInt(bottom)
    }

    private fun readFromParcel(inParcel: Parcel) {
        left = inParcel.readInt()
        top = inParcel.readInt()
        right = inParcel.readInt()
        bottom = inParcel.readInt()
    }

    override fun describeContents(): Int {
        return 0
    }
}

Rect 類別中的封送處理很簡單。請查看 Parcel 的其他方法,瞭解可寫入 Parcel 的其他值類型。

警告:請注意從其他程序接收資料時,可能產生的安全性影響。在這種情況下,Rect 會從 Parcel 讀取四個數字,但您必須確保這些數字在呼叫端嘗試執行的任何操作的可接受值範圍內。如要進一步瞭解如何保護應用程式免受惡意軟體攻擊,請參閱「安全性提示」。

含有 Parcelable 的 Bundle 引數方法

如果方法接受預期包含 Parcelable 的 Bundle 物件,請務必先呼叫 Bundle.setClassLoader(ClassLoader) 設定 Bundle 的類別載入器,再嘗試從 Bundle 讀取。否則,即使應用程式中正確定義了 Parcelable,您仍會遇到 ClassNotFoundException。

舉例來說,請參考下列 .aidl 檔案範例:

// IRectInsideBundle.aidl
package com.example.android;

/** Example service interface. */
interface IRectInsideBundle {
    /** Rect parcelable is stored in the bundle with key "rect". */
    void saveRect(in Bundle bundle);
}
如以下實作所示,在讀取 Rect 之前,ClassLoader 會在 Bundle 中明確設定:
private val binder = object : IRectInsideBundle.Stub() {
    override fun saveRect(bundle: Bundle) {
        bundle.classLoader = classLoader
        val rect = BundleCompat.getParcelable(bundle, "rect", Rect::class.java)
        process(rect) // Do more with the parcelable.
    }
}

呼叫 IPC 方法

如要呼叫以 AIDL 定義的遠端介面,請在呼叫類別中執行下列步驟:

  1. 在專案 src/ 目錄中加入 .aidl 檔案。
  2. 宣告 IBinder 介面的例項,該介面是根據 AIDL 產生。
  3. 實作 ServiceConnection。
  4. 呼叫 Context.bindService(),傳入 ServiceConnection 實作。
  5. 在 onServiceConnected() 的實作中,您會收到名為 service 的 IBinder 執行個體。呼叫 YourInterfaceName.Stub.asInterface((IBinder)service),將傳回的參數轉換為 YourInterface 類型。
  6. 呼叫您在介面上定義的方法。請務必擷取 DeadObjectException 例外狀況,系統會在連線中斷時擲回這類例外狀況。此外,請擷取 SecurityException 例外狀況,當 IPC 方法呼叫中涉及的兩個程序具有衝突的 AIDL 定義時,系統會擲回這類例外狀況。
  7. 如要中斷連線,請使用介面執行個體呼叫 Context.unbindService()。

呼叫 IPC 服務時,請注意以下幾點:

  • 系統會跨程序計算物件的參照次數。
  • 您可以傳送匿名物件做為方法引數。

如要進一步瞭解如何繫結至服務,請參閱「繫結服務總覽」。

以下程式碼範例示範如何呼叫 AIDL 建立的服務,取自 ApiDemos 專案中的遠端服務範例。

private const val BUMP_MSG = 1

class Binding : Activity() {

    /** The primary interface you call on the service.  */
    private var mService: IRemoteService? = null

    /** Another interface you use on the service.  */
    internal var secondaryService: ISecondary? = null

    private lateinit var killButton: Button
    private lateinit var callbackText: TextView
    private lateinit var handler: InternalHandler

    private var isBound: Boolean = false

    /**
     * Class for interacting with the main interface of the service.
     */
    private val mConnection = object : ServiceConnection {

        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            // This is called when the connection with the service is
            // established, giving us the service object we can use to
            // interact with the service.  We are communicating with our
            // service through an IDL interface, so get a client-side
            // representation of that from the raw service object.
            mService = IRemoteService.Stub.asInterface(service)
            killButton.isEnabled = true
            callbackText.text = "Attached."

            // We want to monitor the service for as long as we are
            // connected to it.
            try {
                mService?.registerCallback(mCallback)
            } catch (e: RemoteException) {
                // In this case, the service crashes before we can
                // do anything with it. We can count on soon being
                // disconnected (and then reconnected if it can be restarted)
                // so there is no need to do anything here.
            }

            // As part of the sample, tell the user what happened.
            Toast.makeText(
                    this@Binding,
                    R.string.remote_service_connected,
                    Toast.LENGTH_SHORT
            ).show()
        }

        override fun onServiceDisconnected(className: ComponentName) {
            // This is called when the connection with the service is
            // unexpectedly disconnected&mdash;that is, its process crashed.
            mService = null
            killButton.isEnabled = false
            callbackText.text = "Disconnected."

            // As part of the sample, tell the user what happened.
            Toast.makeText(
                    this@Binding,
                    R.string.remote_service_disconnected,
                    Toast.LENGTH_SHORT
            ).show()
        }
    }

    /**
     * Class for interacting with the secondary interface of the service.
     */
    private val secondaryConnection = object : ServiceConnection {

        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            // Connecting to a secondary interface is the same as any
            // other interface.
            secondaryService = ISecondary.Stub.asInterface(service)
            killButton.isEnabled = true
        }

        override fun onServiceDisconnected(className: ComponentName) {
            secondaryService = null
            killButton.isEnabled = false
        }
    }

    private val mBindListener = View.OnClickListener {
        // Establish a couple connections with the service, binding
        // by interface names. This lets other applications be
        // installed that replace the remote service by implementing
        // the same interface.
        val intent = Intent(this@Binding, RemoteService::class.java)
        intent.action = IRemoteService::class.java.name
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
        intent.action = ISecondary::class.java.name
        bindService(intent, secondaryConnection, Context.BIND_AUTO_CREATE)
        isBound = true
        callbackText.text = "Binding."
    }

    private val unbindListener = View.OnClickListener {
        if (isBound) {
            // If we have received the service, and hence registered with
            // it, then now is the time to unregister.
            try {
                mService?.unregisterCallback(mCallback)
            } catch (e: RemoteException) {
                // There is nothing special we need to do if the service
                // crashes.
            }

            // Detach our existing connection.
            unbindService(mConnection)
            unbindService(secondaryConnection)
            killButton.isEnabled = false
            isBound = false
            callbackText.text = "Unbinding."
        }
    }

    private val killListener = View.OnClickListener {
        // To kill the process hosting the service, we need to know its
        // PID.  Conveniently, the service has a call that returns
        // that information.
        try {
            secondaryService?.pid?.also { pid ->
                // Note that, though this API lets us request to
                // kill any process based on its PID, the kernel
                // still imposes standard restrictions on which PIDs you
                // can actually kill. Typically this means only
                // the process running your application and any additional
                // processes created by that app, as shown here. Packages
                // sharing a common UID are also able to kill each
                // other's processes.
                Process.killProcess(pid)
                callbackText.text = "Killed service process."
            }
        } catch (ex: RemoteException) {
            // Recover gracefully from the process hosting the
            // server dying.
            // For purposes of this sample, put up a notification.
            Toast.makeText(this@Binding, R.string.remote_call_failed, Toast.LENGTH_SHORT).show()
        }
    }

    // ----------------------------------------------------------------------
    // Code showing how to deal with callbacks.
    // ----------------------------------------------------------------------

    /**
     * This implementation is used to receive callbacks from the remote
     * service.
     */
    private val mCallback = object : IRemoteServiceCallback.Stub() {
        /**
         * This is called by the remote service regularly to tell us about
         * new values.  Note that IPC calls are dispatched through a thread
         * pool running in each process, so the code executing here is
         * NOT running in our main thread like most other things. So,
         * to update the UI, we need to use a Handler to hop over there.
         */
        override fun valueChanged(value: Int) {
            handler.sendMessage(handler.obtainMessage(BUMP_MSG, value, 0))
        }
    }

    /**
     * Standard initialization of this activity.  Set up the UI, then wait
     * for the user to interact with it before doing anything.
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.remote_service_binding)

        // Watch for button taps.
        var button: Button = findViewById(R.id.bind)
        button.setOnClickListener(mBindListener)
        button = findViewById(R.id.unbind)
        button.setOnClickListener(unbindListener)
        killButton = findViewById(R.id.kill)
        killButton.setOnClickListener(killListener)
        killButton.isEnabled = false

        callbackText = findViewById(R.id.callback)
        callbackText.text = "Not attached."
        handler = InternalHandler(callbackText)
    }

    private class InternalHandler(
            textView: TextView,
            private val weakTextView: WeakReference<TextView> = WeakReference(textView)
    ) : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                BUMP_MSG -> weakTextView.get()?.text = "Received from service: ${msg.arg1}"
                else -> super.handleMessage(msg)
            }
        }
    }
}