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

Android Service 全解析(四):用 AIDL 打通跨進程遠程服務

編輯:關於 Android 程式設計

當服務與使用者介面不在同一個應用、甚至不在同一個進程時,傳統的 Binder 傳遞方式就不夠用了。AIDL(Android Interface Definition Language)正是為此而生:它讓你只描述介面,工具自動生成跨進程通信所需的樣板代碼。

AIDL 的定義規則

建立一個介面,宣告各種方法,然後做兩件事:讓「介面名」與「方法名」都不帶任何修飾符(不要寫 public、不要寫 abstract),接著把副檔名從 .java 改成 .aidl。注意介面名稱必須與檔名完全一致。

interface IRemoteQuery {
    String queryByNum(int number);
}

重新整理專案後,系統會自動產生對應的 IRemoteQuery.java。這個檔案是理解 AIDL 的關鍵:內部其實是一個同名介面,而介面裡最重要的成員是 Stub 靜態抽象類——它同時繼承了 Binder,並實作了你定義的業務介面。也就是說,Stub 的實例天生就具備「可綁定」與「可執行業務」兩種能力。

接著在客戶端建立一個包名與 aidl 所在包完全一致的資料夾,把 .aidl 檔複製進去,重新整理後客戶端的 gen 目錄也會產生同樣的 IRemoteQuery.java。這一步不能省,因為 aidl 等同於雙方共同遵守的通信協議,必須一式兩份。

自動生成的代碼長什麼樣

public interface IRemoteQuery extends android.os.IInterface {

    public static abstract class Stub extends android.os.Binder
            implements com.cn.aidl.IRemoteQuery {
        private static final java.lang.String DESCRIPTOR = "com.cn.aidl.IRemoteQuery";

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

        public static com.cn.aidl.IRemoteQuery asInterface(android.os.IBinder obj) {
            if ((obj == null)) {
                return null;
            }
            android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
            if (((iin != null) && (iin instanceof com.cn.aidl.IRemoteQuery))) {
                return ((com.cn.aidl.IRemoteQuery) iin);
            }
            return new com.cn.aidl.IRemoteQuery.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_queryByNum: {
                    data.enforceInterface(DESCRIPTOR);
                    int _arg0;
                    _arg0 = data.readInt();
                    java.lang.String _result = this.queryByNum(_arg0);
                    reply.writeNoException();
                    reply.writeString(_result);
                    return true;
                }
            }
            return super.onTransact(code, data, reply, flags);
        }

        private static class Proxy implements com.cn.aidl.IRemoteQuery {
            private android.os.IBinder mRemote;

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

            @Override
            public java.lang.String queryByNum(int number) throws android.os.RemoteException {
                android.os.Parcel _data = android.os.Parcel.obtain();
                android.os.Parcel _reply = android.os.Parcel.obtain();
                java.lang.String _result;
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    _data.writeInt(number);
                    mRemote.transact(Stub.TRANSACTION_queryByNum, _data, _reply, 0);
                    _reply.readException();
                    _result = _reply.readString();
                } finally {
                    _reply.recycle();
                    _data.recycle();
                }
                return _result;
            }
        }

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

    public java.lang.String queryByNum(int number) throws android.os.RemoteException;
}

看懂這段就能理解 AIDL 的全貌:客戶端呼叫 Proxy 的方法,參數被寫進 Parcel,透過 transact() 送到服務端;服務端的 Stub.onTransact() 從 Parcel 還原參數、執行真正的實作,再把結果寫回 reply。

服務端實作

自訂一個類別繼承 Service,內部寫一個 RemoteQueryBinder 繼承 IRemoteQuery.Stub 並實作業務邏輯,最後在 onBind() 中把它回傳給客戶端。

package com.cn.remoteService;

import com.cn.aidl.IRemoteQuery;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

public class RemoteQueryService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return remoteQueryBinder;
    }

    RemoteQueryBinder remoteQueryBinder = new RemoteQueryBinder();

    private String[] names = new String[]{"小明", "小王", "小楊", "小李"};

    private final class RemoteQueryBinder extends IRemoteQuery.Stub {
        @Override
        public String queryByNum(int number) throws RemoteException {
            return query(number);
        }
    }

    public String query(int i) {
        if (i > 0 && i < 5) {
            return names[i - 1];
        }
        return "查詢錯誤,請再次輸入";
    }
}

客戶端實作

因為服務與客戶端不在同一個應用,彼此「看不見」,所以必須用隱式 Intent 激活,這也意味著在清單檔中宣告該服務時,一定要為它加上 intent-filter。

package cn.com.remoteServiceClient;

import com.cn.aidl.IRemoteQuery;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    TextView numberTextView;
    TextView resultTextView;
    Button button;
    RemoteQueryServiceConnection conn = new RemoteQueryServiceConnection();
    IRemoteQuery remoteQueryBinder;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        numberTextView = (TextView) findViewById(R.id.number);
        resultTextView = (TextView) findViewById(R.id.result);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new ButtonOnClickListener());

        Intent service = new Intent();
        service.setAction("com.cn.remoteService.RemoteQueryService");
        bindService(service, conn, this.BIND_AUTO_CREATE);
    }

    private class ButtonOnClickListener implements OnClickListener {
        public void onClick(View v) {
            String number = numberTextView.getText().toString();
            String result;
            try {
                result = remoteQueryBinder.queryByNum(Integer.valueOf(number));
                resultTextView.setText(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private final class RemoteQueryServiceConnection implements ServiceConnection {
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 關鍵:這裡收到的是代理物件,必須轉型為介面
            remoteQueryBinder = IRemoteQuery.Stub.asInterface(service);
        }

        public void onServiceDisconnected(ComponentName name) {
            remoteQueryBinder = null;
        }
    }

    protected void onDestroy() {
        unbindService(conn);
        super.onDestroy();
    }
}

對應的佈局很單純,一個輸入框、一顆按鈕與一個顯示結果的 TextView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/number" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/number" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button"
        android:id="@+id/button" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/result" />
</LinearLayout>

三個最容易出錯的地方

一、忘記在清單檔配置 intent-filter。隱式 Intent 靠 action 比對尋找目標服務,沒有過濾器就永遠找不到。

二、把 IBinder 直接當成業務介面用。本地服務那樣直接轉型之所以可行,是因為 Binder 物件本身就實作了業務介面;但遠程服務收到的其實是 Proxy 代理物件,必須經過 IRemoteQuery.Stub.asInterface(service) 轉換,否則會出現 ClassCastException。

三、aidl 檔只放一邊。它是雙方共同遵守的協議,客戶端與服務端都必須有同一份,且包名一致。

核心總結

把本地服務與遠程服務放在一起對照,會發現它們其實圍繞同一個核心:取得一個 Binder 物件。本地服務的 Binder 類別繼承 Binder 並實作業務介面,因此可直接用該介面接收;遠程服務則由 aidl 自動產生 Stub,它同樣繼承 Binder 並實作業務介面,所以回傳的代理物件一樣能用業務介面接收。差別只在於是否多了一層 Parcel 序列化與 asInterface() 轉換。

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