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

跨行程呼叫 Service:AIDL 遠程服務實作全流程

編輯:關於 Android 程式設計

跨行程溝通在技術史上有過幾種經典方案:早期 CORBA 用它做跨語言的物件呼叫,Java 世界則有 RMI。在 Android 上,對應的做法就是 AIDL 遠程 Service。

Android 的遠程 Service 呼叫概念上與 Java RMI 相似——先定義一個遠程介面,再提供實作類別。關鍵差異在於:RMI 會直接把遠端物件的 Stub 交給客戶端,而 Android 綁定 Service 時,onBind() 回傳的是一個 IBinder;客戶端拿到的其實是這個 Binder 的代理,透過代理再回頭呼叫遠端 Service 的方法與屬性。

第一步:定義 AIDL 介面

AIDL 是 Android Interface Definition Language。幾個硬性規則:

  • 副檔名必須是 .aidl,放在 src 下同樣的套件路徑底下。
  • 介面中的參數型別,除了基本型別、String、List、Map、CharSequence 之外,其他自訂型別都必須另外 import——即使與介面位於同一個套件也一樣。
  • 使用 ADT 或 Android Studio 開發時,工具會自動產生對應的 Java Stub 與 Proxy 實作,不需手寫。
// IMessage.aidl
package com.lovo.service;

interface IMessage {
    int getFlag();
    String getMessage(String msg);
}

第二步:實作遠端 Service

package com.lovo.service;

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

public class RemoteService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        MyMessage message = new MyMessage();
        return message;
    }
}

第三步:AIDL 介面的實作類別

package com.lovo.service;

public class MyMessage extends IMessage.Stub {

    @Override
    public int getFlag() {
        return 100;
    }

    @Override
    public String getMessage(String msg) {
        return msg + "Android!";
    }
}

記得在 AndroidManifest.xml 中註冊這個 Service,並為它加上 android:process=":remote"(或其他行程名稱),否則它就只是同行程的本地 Service,AIDL 的意義就沒了。

第四步:客戶端綁定

package com.lovo.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.lovo.conn.RemoteServiceConnection;
import com.lovo.lesson10.R;

public class StartRemoteActivity extends Activity {

    private Button startServiceBtn;

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

        startServiceBtn = (Button) findViewById(R.id.remote_main_btn_startserver);
        startServiceBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("com.lovo.service.REMOTE_SERVICE");
                bindService(intent, new RemoteServiceConnection(), BIND_AUTO_CREATE);
            }
        });
    }
}

第五步:ServiceConnection 取得代理並呼叫

package com.lovo.conn;

import com.lovo.service.IMessage;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class RemoteServiceConnection implements ServiceConnection {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // 把 Binder 代理轉換為可呼叫的介面物件
        IMessage message = IMessage.Stub.asInterface(service);
        try {
            Log.i("訪問遠程方法:",
                    message.getFlag() + " " + message.getMessage("I like "));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        // 服務意外中止時的處理
    }
}

版面檔只有一顆按鈕,此處省略。以上就是最基礎的遠程方法呼叫,實際專案中可以用 AIDL 傳遞自訂的 Parcelable 物件。

實作時容易忽略的重點

RemoteException 必須處理。遠端行程隨時可能被系統回收,所有跨行程呼叫都要包在 try-catch 裡,並在 onServiceDisconnected() 中決定是否重連。呼叫也要放在背景執行緒,若在主執行緒上做同步 IPC,資料量大時會直接 ANR。

傳遞自訂型別要 implements Parcelable。除了前述的 import 規則,AIDL 中使用的自訂物件還必須實作 Parcelable,並在 .aidl 檔中補上一行同套件的 package 宣告。若是集合型別,元素也必須是 Parcelable 或支援的型別。

注意 Binder 交易緩衝區上限。單次 Binder 交易的資料量約 1MB(且需與其他行程共用),傳送大張圖片或大量資料會失敗,這種情況應改用其他通道(例如透過 ContentProvider 傳 URI,再由接收方自行讀取)。

unbindService 別忘記。綁定後若未解除,Service 會一直留存,造成記憶體與生命週期問題。建議在 onDestroy() 中呼叫,並以旗標避免重複綁定。

若只是單向通知、不需要回傳結果,用 Messenger 會比 AIDL 簡單許多;AIDL 的價值在於需要「雙向、多方法、可併發」的正式介面時才值得付出這些複雜度。

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