Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 進程間通信實戰:用 AIDL 打通 Activity 與 Service

你會點開這篇,大概已經知道進程間通信、AIDL 與 Binder 是什麼,也有個大致印象。所以這裡不再複製網路上氾濫的轉貼,也不逐句翻譯冗長的官方文件,直接上例子。

延伸閱讀:docs/guide/developing/tools/aidl.html(AIDL)、docs/reference/android/os/IBinder.html(IBinder)、docs/reference/android/os/Binder.html(Binder)。以我的粗淺經驗,AIDL 的用武之地幾乎都與 Service 相關,因此你也需要具備一些 Service 基礎。

示例結構

  1. mAIDLActivity:繼承 Activity,放三個按鈕,文字分別為 StartService、StopService、CallbackTest。
  2. mAIDLService:繼承 Service。點擊 CallbackTest 時,Activity 呼叫 Service 端 Stub 物件的 invokCallBack(),該方法再回頭呼叫 Activity 端 Stub 物件的 performAction(),在螢幕上彈出 Toast。功能本身沒什麼意義,重點是展示 AIDL 雙向通信怎麼寫。
  3. 兩個 aidl 檔:forService.aidl 與 forActivity.aidl,分別定義 Service 與 Activity 各自需要暴露的接口。
  4. XML 與 manifest 從略。manifest 中 Service 的宣告可寫成:
    <service android:name=".mAIDLService" android:process=":remote"> </service>

開發環境為 Eclipse。

aidl 檔內容

forActivity.aidl:

package com.styleflying.AIDL;
interface forActivity {
    void performAction();
}

forService.aidl:

package com.styleflying.AIDL;
import com.styleflying.AIDL.forActivity;
interface forService {
    void registerTestCall(forActivity cb);
    void invokCallBack();
}

兩個檔案與 Java 原始碼放在同一層,Eclipse 會自動編譯成 forActivity.java 與 forService.java,輸出到 gen 目錄。

自動生成的程式碼長什麼樣

以 forActivity.java 為例(省略部分以便閱讀):

/* This file is auto-generated. DO NOT MODIFY. */
package com.styleflying.AIDL;

public interface forActivity extends android.os.IInterface {
    /** Local-side IPC implementation stub class. */
    public static abstract class Stub extends android.os.Binder
            implements com.styleflying.AIDL.forActivity {
        private static final java.lang.String DESCRIPTOR = "com.styleflying.AIDL.forActivity";

        public Stub() { this.attachInterface(this, DESCRIPTOR); }

        public static com.styleflying.AIDL.forActivity asInterface(android.os.IBinder obj) {
            if ((obj == null)) { return null; }
            android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
            if (((iin != null) && (iin instanceof com.styleflying.AIDL.forActivity))) {
                return ((com.styleflying.AIDL.forActivity) iin);
            }
            return new com.styleflying.AIDL.forActivity.Stub.Proxy(obj);
        }

        public android.os.IBinder asBinder() { return this; }

        @Override 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_performAction: {
                    data.enforceInterface(DESCRIPTOR);
                    this.performAction();
                    reply.writeNoException();
                    return true;
                }
            }
            return super.onTransact(code, data, reply, flags);
        }

        private static class Proxy implements com.styleflying.AIDL.forActivity {
            private android.os.IBinder mRemote;
            Proxy(android.os.IBinder remote) { mRemote = remote; }
            public android.os.IBinder asBinder() { return mRemote; }
            public java.lang.String getInterfaceDescriptor() { return DESCRIPTOR; }
            public void performAction() throws android.os.RemoteException {
                android.os.Parcel _data = android.os.Parcel.obtain();
                android.os.Parcel _reply = android.os.Parcel.obtain();
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    mRemote.transact(Stub.TRANSACTION_performAction, _data, _reply, 0);
                    _reply.readException();
                } finally {
                    _reply.recycle();
                    _data.recycle();
                }
            }
        }
        static final int TRANSACTION_performAction = (IBinder.FIRST_CALL_TRANSACTION + 0);
    }
    public void performAction() throws android.os.RemoteException;
}

forService.java 結構幾乎相同,差別只在多了一個帶 Parcelable/接口參數的方法,其 Proxy 實作會用 writeStrongBinder(cb.asBinder()) 把對端物件寫進 Parcel,並在 Stub 側以 asInterface(data.readStrongBinder()) 還原。

看懂 Stub 與 Proxy

兩個檔案的骨架一致:接口內部有一個抽象類 Stub,Stub 裡又有一個 Proxy。Stub 提供靜態方法 asInterface(),內部有多條 return:當呼叫方與被呼叫方在同一進程時,它直接回傳本地實作物件;否則回傳一個新建的 Proxy,由 Proxy 把呼叫序列化後透過 Binder 轉送。

Stub 對我們最有用的一點是它繼承了 Binder。任何繼承 Binder 的類別,其實作物件都能被遠端進程使用——前提是對方拿到了這個物件的引用。所以 Service 中若有 Stub 子類的物件,該物件的方法就能在 Activity 中被呼叫;反過來也成立。Binder 的細節網上不乏好文章,看不太懂也不影響你把這個例子跑起來。

Copyright © Linux教程網 All Rights Reserved