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

AIDL 與遠程服務:Android 跨進程通訊完整流程

編輯:關於 Android 程式設計

Android 中每個 App 各自獨立於自己的進程,Java 又不支援跨進程的記憶體共享,因此要傳物件,就得先把它拆解成作業系統能懂的資料格式,在對岸再重組回來。JavaEE 用 RMI 搭配序列化處理這件事,Android 則用 AIDL。

AIDL 是什麼

AIDL 是介面描述語言,用來約束兩個進程的通訊規則,並讓編譯器據此產生程式碼,完成裝置上的行程間通訊(IPC)。運作方式與 CORBA 相似:通訊內容先被轉成 AIDL 協議訊息送達對方,對方再還原成物件。因為需要雙向轉換,Android 以代理類在背後完成序列化與反序列化,而這些代理類由編譯器自動產生,對開發者完全透明。

Step 1:定義 aidl 檔

假設 App B 要以 Service 形式對外提供 download(String path),先在 B 的 cn.itcast.aidl 下建立 IDownloadService.aidl:

package cn.itcast.aidl;

interface IDownloadService {
    void download(String path);
}

存檔後,Eclipse 會自動在 gen 目錄產生 IDownloadService.java,其中有一個 Stub 抽象類,包含你定義的方法與若干輔助方法。特別注意 asInterface(IBinder):遠程服務回傳給客戶端的是代理物件,不能直接強轉成介面型別,必須透過它來轉換。

撰寫 aidl 的六個規則

  1. 介面名稱與 aidl 檔名相同。
  2. 介面與方法前不加 public、private、protected,也不能用 final、static。
  3. 預設支援 Java 基本型別(int、long、boolean 等)與 String、List、Map、CharSequence,使用時不需 import;List 與 Map 的元素型別也必須在支援範圍內。
  4. 自訂型別作為參數或回傳值時,必須實作 Parcelable。
  5. 自訂型別與其他 aidl 產生的介面型別,在 aidl 檔中要顯式 import,即使彼此在同一 package。
  6. 所有非 Java 基本型別的參數都要標註 in、out 或 inout,指明方向;Java 原始型別預設為 in,不可標其他。

Step 2:實作 Stub

public class ServiceBinder extends IDownloadService.Stub {
    @Override
    public void download(String path) throws RemoteException {
        Log.i("DownloadService", path);
    }
}

Step 3:用 Service 承載並發布

public class DownloadService extends Service {
    private ServiceBinder serviceBinder = new ServiceBinder();

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

其他應用可用隱式 Intent 找到它,action 名稱自訂,並在清單檔註冊:

<service android:name=".DownloadService">
    <intent-filter>
        <action android:name="cn.itcast.process.aidl.DownloadService" />
    </intent-filter>
</service>

Step 4:客戶端接入

把 aidl 檔連同 package 一起複製到客戶端專案,Eclipse 會同步產生介面檔,接著就能綁定並呼叫:

private IDownloadService downloadService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    bindService(new Intent("cn.itcast.process.aidl.DownloadService"),
            serviceConnection, BIND_AUTO_CREATE);
}

private ServiceConnection serviceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        downloadService = IDownloadService.Stub.asInterface(service);
        try {
            downloadService.download("https://www.itcast.cn");
        } catch (RemoteException e) {
            Log.e("ClientActivity", e.toString());
        }
    }
    @Override
    public void onServiceDisconnected(ComponentName name) {
        downloadService = null;
    }
};

記得在 onDestroy 呼叫 unbindService。若客戶端與服務端不在同一進程,所有方法呼叫都是跨進程的,因此務必處理 RemoteException,並避免在方法裡傳遞龐大物件——Parcel 有大小限制,超過會直接拋出 TransactionTooLargeException。

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