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

Android IPC 之 AIDL(一):從零跑通一次跨進程調用

編輯:關於 Android 程式設計

IPC 是 Inter-Process Communication 的縮寫,也就是跨進程通信。Android 中實現 IPC 的方式不少:文件共享、ContentProvider、Broadcast、Socket 都能勝任,它們各有側重。而在接口調用語義比較複雜的場景下,最常用的兩種是 Messenger 和 AIDL,而 Messenger 的底層實現,恰恰就是 AIDL。

本文先不糾結原理,直接動手跑通一次最簡單的跨進程調用,把使用路徑走順,下一篇再拆細節。

用一個例子說清需求

假設有個「兩數相加」的任務,客戶端因為某種原因沒法自己算,需要把任務交給另一個進程中的服務端完成,再把結果取回來。這就是最典型的 AIDL 使用場景。

第一步:創建 AIDL 接口

按下面的方式新建一個 AIDL 文件:

Android Studio 會自動幫你生成目錄結構,位置通常在 src/main/aidl 下,並與 java 目錄平級:

在其中聲明一個接口,以及一個希望服務端實現的方法:

package com.vera.aidltest;

interface IMyAdd {
    int myAdd(int num_a, int num_b);
}

AIDL 支持哪些數據類型

並不是所有類型都能寫進 .aidl 文件,支持範圍如下:

  • Java 中的全部基本數據類型。
  • String 與 CharSequence。
  • List 與 Map,且兩者的元素必須是 AIDL 支持的數據類型。
  • AIDL 自動生成的接口,需要 import(即使處於同一個包中)。
  • 實現了 android.os.Parcelable 接口的類的對象。同樣需要 import(即使同包),並且必須新建一個與其同名的 AIDL 文件,在其中聲明該類為 Parcelable。

最後一條最容易漏。自定義 Parcelable 對象要在 AIDL 中使用,光實現接口是不夠的,還得配一個同名的 .aidl 聲明文件,否則編譯期就會報錯。

第二步:看看系統生成了什麼

接口定義好後,系統會在 app/build/generated/source/aidl/debug 目錄下生成對應的 Java 文件:

package com.vera.aidltest;

public interface IMyAdd extends android.os.IInterface {

    /** Local-side IPC implementation stub class. */
    public static abstract class Stub extends android.os.Binder
            implements com.vera.aidltest.IMyAdd {

        private static final java.lang.String DESCRIPTOR = "com.vera.aidltest.IMyAdd";

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

        /**
         * Cast an IBinder object into an IMyAdd interface,
         * generating a proxy if needed.
         */
        public static com.vera.aidltest.IMyAdd asInterface(android.os.IBinder obj) {
            if (obj == null) {
                return null;
            }
            android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
            if (iin != null && iin instanceof com.vera.aidltest.IMyAdd) {
                return (com.vera.aidltest.IMyAdd) iin;
            }
            return new com.vera.aidltest.IMyAdd.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_myAdd:
                    data.enforceInterface(DESCRIPTOR);
                    int _arg0 = data.readInt();
                    int _arg1 = data.readInt();
                    int _result = this.myAdd(_arg0, _arg1);
                    reply.writeNoException();
                    reply.writeInt(_result);
                    return true;
            }
            return super.onTransact(code, data, reply, flags);
        }

        /** 客戶端使用的代理 */
        private static class Proxy implements com.vera.aidltest.IMyAdd {
            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 int myAdd(int num_a, int num_b)
                    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(num_a);
                    _data.writeInt(num_b);
                    mRemote.transact(Stub.TRANSACTION_myAdd, _data, _reply, 0);
                    _reply.readException();
                    _result = _reply.readInt();
                } finally {
                    _reply.recycle();
                    _data.recycle();
                }
                return _result;
            }
        }

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

    public int myAdd(int num_a, int num_b) throws android.os.RemoteException;
}

代碼很長,本節先不逐行分析,只要抓住三點:

  1. 生成了一個名為 IMyAdd 的接口,繼承 android.os.IInterface。
  2. 內部有一個靜態抽象類 Stub,它繼承 Binder 並實現了 IMyAdd。
  3. 接口中聲明了 myAdd() 方法。

為什麼 Stub 是抽象類?因為它雖然實現了 IMyAdd 接口,卻沒有真正實現方法體——真正的實現要放到服務端去寫。

第三步:寫服務端

本例中,客戶端就是一個 Activity,服務端就是一個 Service。這裡我們把它們放在同一個應用中,只不過通過某種方式讓它們跑在不同進程。

新建一個名為 ServerService 的 Service:

package com.vera.aidltest;

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

public class ServerService extends Service {

    private Binder mBinder = new IMyAdd.Stub() {

        @Override
        public int myAdd(int num_a, int num_b) throws RemoteException {
            int result = num_a + num_b;
            Log.d("ServerService", "the result of " + num_a
                    + " and " + num_b + " is " + result);
            return result;
        }
    };

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

邏輯非常簡單:創建一個 Binder 對象,並在 onBind() 中返回它。這個 Binder 就是我們繼承 IMyAdd.Stub 實現了接口方法的匿名對象,業務邏輯寫在 myAdd() 裡即可。

接著,必須把這個 Service 放到一個獨立進程中,否則就不叫跨進程通信了。修改 AndroidManifest.xml:

<service
    android:name=".ServerService"
    android:process=":remote" />

進程名以冒號開頭表示這是應用私有進程,系統會按需創建。此時 logcat 裡就能明顯看到兩組不同的進程標識。

第四步:寫客戶端

package com.vera.aidltest;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class ClientActivity extends AppCompatActivity {

    Button mButton;

    private ServiceConnection myConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            IMyAdd mMyAdd = IMyAdd.Stub.asInterface(iBinder);
            try {
                int result = mMyAdd.myAdd(1, 2);
                Log.d("ClientActivity", "get the result is " + result);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

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

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

        mButton = (Button) findViewById(R.id.activity_client_mbutton);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ClientActivity.this, ServerService.class);
                bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
            }
        });
    }

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

逐段解釋:

先創建一個 ServiceConnection 匿名類並實例化。然後在 Button 的點擊事件裡調用 bindService() 綁定服務。這個方法接收三個參數:Intent 對象、ServiceConnection 實例、以及一個標誌位。BIND_AUTO_CREATE 表示 Activity 與 Service 綁定後,若服務尚未創建則自動創建。

最後重寫 onDestroy(),解除綁定。這一步不能省,否則會產生 ServiceConnection 洩露,屏幕旋轉幾次後就可能引發崩潰。

重點在 ServiceConnection 內部:它重寫了 onServiceConnected() 與 onServiceDisconnected(),分別在綁定成功與連接斷開時回調。在 onServiceConnected() 裡,我們調用 Stub 的 asInterface() 方法,得到一個 Binder 代理對象,並向上轉型為客戶端可識別的 AIDL 接口類型。這一步是整個流程的樞紐——它會判斷當前是否同進程,同進程直接返回本地實現,跨進程則包裝成 Proxy。

拿到這個對象後,剩下就是普通的方法調用了。

運行驗證

運行程序,點擊 Button,查看 logcat:

在 com.vera.aidltest 進程中,客戶端打印出「get the result is 3」;在 com.vera.aidltest:remote 進程中,服務端打印出 1 和 2 相加等於 3。通信成功。

步驟回顧

  1. 建立一個 AIDL 文件,在其中定義接口,接口中包含希望服務端實現的方法聲明。
  2. 在服務端把實現好方法的 Stub 對象通過 onBind() 返回,並在清單文件中用 android:process 把它放到獨立進程。
  3. 在客戶端綁定服務,重寫 ServiceConnection 中的方法,在其中獲得 Binder 對象、調用 asInterface 轉型,然後調用服務端的接口方法。

跨應用時的關鍵差異

上面的例子把客戶端和服務端放在同一個應用裡,只靠 android:process 拆分進程。但更常見的情況是它們分屬兩個不同的應用,這時有一件事必須做:把整個 aidl 目錄的內容複製一份到客戶端工程。

原因是客戶端與服務端的 AIDL 包結構必須保持完全一致,包括包名和文件路徑。一旦不一致,Binder 傳輸過程中自定義對象的反序列化就會失敗,跨進程通信直接不可用。這個坑的表現通常是 ClassNotFoundException 或者對象字段全為默認值,排查起來頗費時間。

另外要注意,跨進程調用會拋出 RemoteException,這是一個受檢異常,所有 AIDL 方法調用都必須放在 try-catch 中處理。同時,如果服務端進程意外死亡,客戶端會收到 onServiceDisconnected() 回調,此時 remoteService 引用已失效,需要做好重連邏輯。

下一篇會把 Binder 的底層原理、Parcel 的序列化細節,以及自定義 Parcelable 對象在 AIDL 中的完整用法再展開講。

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