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

Android 進程間通訊:AIDL 從流程到完整實作範例

編輯:關於 Android 程式設計

一、前言

Android 的 RPC 機制參考自 Java 的 RMI(Remote Method Invocation),目的是讓一個行程能使用另一個行程中的遠端物件。Android 用 AIDL(Android Interface Definition Language)來描述這套介面:開發者定義一組方法,再透過遠端 Service 作為代理;客戶端在綁定這個 Service 時取得遠端物件,之後就能像呼叫本地方法一樣使用它。

二、整體流程

1. 定義一個 .aidl 介面檔,ADT 會自動在 gen 目錄下產生對應的 .java 檔(自動產生,不可手改)。

2. 自動產生的 .java 中有一個抽象的 Stub 類別,建立一個繼承 Stub 的子類別並實作 .aidl 中定義的方法。

3. 建立一個 Service 子類別,在 onCreate 中建立步驟 2 的物件,在 onBind 中把它回傳。

4. 在 Activity 中呼叫 bindService(it, conn, BIND_AUTO_CREATE) 送出綁定請求。

5. 綁定成功後,在 ServiceConnection.onServiceConnected 中取得步驟 3 的物件。

6. 在 AndroidManifest.xml 中註冊這個遠端 Service。

三、完整範例

3.1 定義 .aidl 檔

package com.chris.rpc.aidl;

interface ITest {
    void setCustomerName(String name);
    String getCustomerName();
}

很簡單的兩個方法。ADT 會自動在 gen 目錄下產生 ITest.java,內容大致如下(可重點看 Stub、asInterface、onTransact 三處):

/*
 * This file is auto-generated.  DO NOT MODIFY.
 */
package com.chris.rpc.aidl;

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

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

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

        @Override 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_setCustomerName: {
                    data.enforceInterface(DESCRIPTOR);
                    java.lang.String _arg0;
                    _arg0 = data.readString();
                    this.setCustomerName(_arg0);
                    reply.writeNoException();
                    return true;
                }
                case TRANSACTION_getCustomerName: {
                    data.enforceInterface(DESCRIPTOR);
                    java.lang.String _result = this.getCustomerName();
                    reply.writeNoException();
                    reply.writeString(_result);
                    return true;
                }
            }
            return super.onTransact(code, data, reply, flags);
        }

        private static class Proxy implements com.chris.rpc.aidl.ITest
        {
            private android.os.IBinder mRemote;

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

            @Override public android.os.IBinder asBinder() {
                return mRemote;
            }

            public java.lang.String getInterfaceDescriptor() {
                return DESCRIPTOR;
            }

            @Override public void setCustomerName(java.lang.String name)
                    throws android.os.RemoteException {
                android.os.Parcel _data = android.os.Parcel.obtain();
                android.os.Parcel _reply = android.os.Parcel.obtain();
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    _data.writeString(name);
                    mRemote.transact(Stub.TRANSACTION_setCustomerName, _data, _reply, 0);
                    _reply.readException();
                } finally {
                    _reply.recycle();
                    _data.recycle();
                }
            }

            @Override public java.lang.String getCustomerName()
                    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);
                    mRemote.transact(Stub.TRANSACTION_getCustomerName, _data, _reply, 0);
                    _reply.readException();
                    _result = _reply.readString();
                } finally {
                    _reply.recycle();
                    _data.recycle();
                }
                return _result;
            }
        }

        static final int TRANSACTION_setCustomerName = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
        static final int TRANSACTION_getCustomerName = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
    }

    public void setCustomerName(java.lang.String name) throws android.os.RemoteException;
    public java.lang.String getCustomerName() throws android.os.RemoteException;
}

3.2 建立 Stub 子類別並實作介面

package com.chris.rpc.aidl;

import android.os.RemoteException;
import android.util.Log;

import com.chris.rpc.aidl.ITest.Stub;

public class MyTest extends Stub {

    private final static String TAG = "ChrisRpcAidl";
    private String strName = "";

    @Override
    public void setCustomerName(String name) throws RemoteException {
        Log.d(TAG, "[MyTest] setCustomerName name = " + name);
        strName = name;
    }

    @Override
    public String getCustomerName() throws RemoteException {
        Log.d(TAG, "[MyTest] getCustomerName name = " + strName);
        return strName;
    }
}

3.3 建立遠端 Service

package com.chris.rpc.aidl;

import com.chris.rpc.aidl.ITest.Stub;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {

    private final static String TAG = "ChrisRpcAidl";
    private Stub mTest = null;

    @Override
    public IBinder onBind(Intent arg0) {
        Log.d(TAG, "onBind ...");
        return mTest;
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate ...");
        mTest = new MyTest();
        super.onCreate();
    }
}

3.4 在 Activity 中綁定並取得物件

package com.chris.rpc.aidl;

import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;

public class MainActivity extends Activity {

    private final static String TAG = "ChrisRpcAidl";
    private final static String SERVICE_ACTION = "com.chris.rpc.aidl.action.MYSERVICE";
    private ITest mTest = null;

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

        Intent it = new Intent();
        it.setAction(SERVICE_ACTION);
        // 送出綁定 Service 請求,成功後會回呼 ServiceConnection
        bindService(it, conn, BIND_AUTO_CREATE);
    }

    private ServiceConnection conn = new ServiceConnection() {

        // 綁定成功,回傳的是 IBinder,需透過 asInterface 轉成自訂的 ITest
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected ...");

            mTest = ITest.Stub.asInterface(service);
            if (mTest != null) {
                try {
                    mTest.setCustomerName("chris");
                    Log.d(TAG, "-------------------");
                    Log.d(TAG, "get name = " + mTest.getCustomerName());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };
}

3.5 在 AndroidManifest.xml 註冊遠端 Service

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.chris.rpc.aidl"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="10" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name="com.chris.rpc.aidl.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name="com.chris.rpc.aidl.MyService">
            <intent-filter>
                <action android:name="com.chris.rpc.aidl.action.MYSERVICE" />
            </intent-filter>
        </service>
    </application>

</manifest>

3.6 執行結果

四、小結

理解 AIDL 的關鍵,是搞清楚自動產生的介面類別中那三個方法:Stub 負責在本地端承接 Binder 呼叫,asInterface 負責把 IBinder 轉成可用的介面(同行程時直接回傳本地物件,跨行程時才包成 Proxy),onTransact 則負責把 Parcel 中的參數解出來並分派到對應方法。這些在 Android Java Framework 裡都有對應實作,最終仍要落到 native 層由 Binder 驅動完成。

AIDL 最典型的應用場景就是音樂播放器這類服務:各個 Activity 與播放 Service 綁定之後,都能透過同一組介面控制播放、暫停、切歌等狀態,而不必各自維護一份狀態。若要進一步深入,就必須理解 Binder 在 framework 層的運作方式,那是另一個主題了。

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