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

Android AIDL 跨進程通信詳解:以加法服務為例的雙端實作

編輯:關於 Android 程式設計

近期研究 Android 二次開發時,接觸到一種常見做法:透過 AIDL 對外暴露接口,讓其他應用可以呼叫。這也說明了 AIDL 的本質——兩個應用之間的跨進程通信。本文以兩個專案為例:ServerDemo 作為服務端提供加法計算,ClientDemo 作為客戶端呼叫該接口並顯示結果。

什麼是 AIDL

AIDL 是 Android Interface Definition Language 的縮寫,是 Android 內部進程通信(IPC, Inter-Process Communication)的接口描述語言。透過它我們可以定義進程間的通信契約,系統再依此自動生成必要的 Binder 樣板程式碼。

整體結構與效果

服務端介面幾乎是空的,重點是那個加法服務;客戶端則有兩個輸入框與一顆計算鈕。

服務端實作

1. 定義 AIDL 檔

只要使用 Eclipse 加 ADT 開發,AIDL 檔會像資源檔一樣被自動編譯成 Java 進入 gen 目錄,不需手動處理。

// IBoardADDInterface.aidl
package com.example.server;

interface IBoardADDInterface {
    int add(int nValue1, int nValue2);
}

編譯後生成的 IBoardADDInterface.java 大致如下,可以順便理解 Binder 的運作方式:

public interface IBoardADDInterface extends android.os.IInterface {

    public static abstract class Stub extends android.os.Binder
            implements com.example.server.IBoardADDInterface {

        private static final String DESCRIPTOR = "com.example.server.IBoardADDInterface";

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

        // 把 IBinder 轉成接口,失敗則建立 Proxy
        public static com.example.server.IBoardADDInterface asInterface(android.os.IBinder obj) {
            if (obj == null) return null;
            android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
            if (iin != null && iin instanceof com.example.server.IBoardADDInterface) {
                return (com.example.server.IBoardADDInterface) iin;
            }
            return new com.example.server.IBoardADDInterface.Stub.Proxy(obj);
        }

        @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_add:
                    data.enforceInterface(DESCRIPTOR);
                    int arg0 = data.readInt();
                    int arg1 = data.readInt();
                    int result = this.add(arg0, arg1);
                    reply.writeNoException();
                    reply.writeInt(result);
                    return true;
            }
            return super.onTransact(code, data, reply, flags);
        }

        private static class Proxy implements com.example.server.IBoardADDInterface {
            private final android.os.IBinder mRemote;

            Proxy(android.os.IBinder remote) { mRemote = remote; }

            @Override
            public int add(int nValue1, int nValue2) throws android.os.RemoteException {
                android.os.Parcel data = android.os.Parcel.obtain();
                android.os.Parcel reply = android.os.Parcel.obtain();
                int result;
                try {
                    data.writeInterfaceToken(DESCRIPTOR);
                    data.writeInt(nValue1);
                    data.writeInt(nValue2);
                    mRemote.transact(Stub.TRANSACTION_add, data, reply, 0);
                    reply.readException();
                    result = reply.readInt();
                } finally {
                    reply.recycle();
                    data.recycle();
                }
                return result;
            }
        }

        static final int TRANSACTION_add =
                (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
    }

    int add(int nValue1, int nValue2) throws android.os.RemoteException;
}

讀完這份自動生成的程式碼,AIDL 的原理就透明了:參數透過 Parcel 序列化寫入,呼叫走 transact,結果再從 reply 讀回。所謂「跨進程呼叫」,就是這套 Parcel 打包與 Binder 轉發的過程。

2. 實作加法服務

public class CaculateAddService extends Service {

    private static final String CACULATE_ADD = "COM.CACULATE.ADD";

    @Override
    public IBinder onBind(Intent intent) {
        if (CACULATE_ADD.equals(intent.getAction())) {
            return mBinder;
        }
        return null;
    }

    // AIDL 接口的實作,業務邏輯寫在這裡
    private final IBinder mBinder = new IBoardADDInterface.Stub() {
        @Override
        public int add(int nValue1, int nValue2) throws RemoteException {
            Log.i("Show", nValue1 + " ,,, " + nValue2);
            return nValue1 + nValue2;
        }
    };
}

用 action 字串來辨識服務,是為了讓同一個 App 能提供多種服務時可以分流;action 名稱由開發者自訂。

3. 在 AndroidManifest.xml 註冊

<service android:name="com.example.server.CaculateAddService">
    <intent-filter>
        <action android:name="COM.CACULATE.ADD" />
    </intent-filter>
</service>

服務端到此完成。Activity 幾乎沒寫什麼,因為整個重點就是 Service 與 AIDL。

客戶端實作

1. 複製 AIDL 檔

把服務端的 IBoardADDInterface.aidl 原封不動複製到客戶端,套件名稱必須保持一致,否則 DESCRIPTOR 對不上,asInterface 會永遠回傳 Proxy 而無法命中本地實作。

package com.example.server;

interface IBoardADDInterface {
    int add(int nValue1, int nValue2);
}

2. 綁定服務的管理類

public class CaculateManager {

    private static final String CACULATE_ADD = "COM.CACULATE.ADD";

    private IBoardADDInterface mService = null;
    private Context mContext = null;

    public void bindService(Context context) {
        mContext = context;
        context.bindService(new Intent(CACULATE_ADD),
                serviceConnection, Context.BIND_AUTO_CREATE);
    }

    public void unbindService() {
        if (mContext != null) {
            mContext.unbindService(serviceConnection);
        }
    }

    public int caculateAdd(int nValue1, int nValue2) {
        if (mService == null) return 0;
        try {
            return mService.add(nValue1, nValue2);
        } catch (Exception e) {
            return 0;
        }
    }

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 關鍵:把 IBinder 轉成 AIDL 接口
            mService = IBoardADDInterface.Stub.asInterface(service);
        }
    };
}

這個類封裝了綁定、解綁與接口呼叫三件事。注意 mService 必須在 onServiceConnected 之後才不為 null,所以呼叫時機要放在綁定成功之後。

3. Activity 取得輸入並呼叫接口

public class MainActivity extends Activity {

    private final CaculateManager caculateManager = new CaculateManager();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        caculateManager.bindService(this);

        findViewById(R.id.button1).setOnClickListener(v -> {
            EditText et1 = findViewById(R.id.editText1);
            EditText et2 = findViewById(R.id.editText2);
            int v1 = Integer.parseInt(et1.getText().toString().trim());
            int v2 = Integer.parseInt(et2.getText().toString().trim());
            int result = caculateManager.caculateAdd(v1, v2);
            ((TextView) findViewById(R.id.textView1))
                    .setText("計算結果:" + result);
        });
    }

    @Override
    protected void onDestroy() {
        caculateManager.unbindService();
        super.onDestroy();
    }
}

4. 版面配置

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="使用 AIDL 服務調用其他程序計算,返回結果" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberDecimal" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberDecimal" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="加法計算" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="計算結果:" />
</LinearLayout>

實作時要留意的幾點

  • 兩端的 AIDL 檔套件名稱與方法簽名必須完全一致。
  • onServiceConnected 之前呼叫會拿到 null,UI 上最好做可用性判斷。
  • 記得在 onDestroy 中 unbindService,否則容易發生 ServiceConnection 洩漏。
  • 若方法回傳 RemoteException,呼叫端務必捕捉;跨進程呼叫也可能因對方進程結束而失敗。
  • 本例只是同機兩個 App 的示範;若要真正對外開放,還需自行加上身分驗證,因為 AIDL 暴露的接口對任何可安裝的應用都是可呼叫的。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved