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

Android 遠端服務 Service 完全解析:AIDL 與跨進程通訊(IPC)實作教學

編輯:關於 Android 程式設計

前言

Service 是 Android 四大組件之一,應用場景極為廣泛。本文聚焦其中一種實務上很常見的用法——遠端 Service,並從底層的 AIDL 與 IPC 機制講起,搭配完整範例帶你走一遍開發流程。


目錄導覽


一、遠端服務與本地服務的差異

兩者最關鍵的區別在於執行所在的行程(Process)是否相同。遠端 Service 與呼叫方分屬不同行程,也就是說它被執行在另一個行程裡;而本地 Service 則與呼叫方共享同一個行程。


二、什麼時候會用到遠端服務

最典型的情境是:多個 App 共用同一個背景服務。

也就是說,一個遠端 Service 需要同時與多個 App 的組件(四大組件)溝通。


三、實作前的基礎知識

想讓遠端 Service 與多個 App 組件完成跨行程通訊(IPC),就必須使用 AIDL。

IPC:Inter-Process Communication,跨行程通訊。
AIDL:Android Interface Definition Language,Android 介面定義語言,用於讓某個 Service 與多個 App 組件進行跨行程通訊,進而實現多個 App 共用同一個 Service 的效果。

在多行程通訊裡,通常會有兩個角色(以最簡單的架構為例):伺服器端與用戶端。

伺服器端(Service)

步驟一:建立並定義 AIDL 檔,宣告這個服務要對外提供的介面。
步驟二:在 Service 子類別中實作 AIDL 定義的介面方法,並處理生命週期相關方法(onCreate、onBind 等)。
步驟三:在 AndroidManifest.xml 中註冊服務,並宣告為遠端服務。

用戶端(Client)

步驟一:把伺服器端的 AIDL 檔複製到自己的專案目錄。
步驟二:透過 Stub.asInterface 取得伺服器端的 Binder,依需求呼叫服務提供的介面方法。
步驟三:以 Intent 指定伺服器端服務的名稱與所在套件,綁定遠端 Service。

以下用一個完整範例說明實際用法。


四、完整實作範例

範例情境:用戶端遠端呼叫伺服器端的遠端 Service。

4.1 伺服器端(Service)

先建立伺服器端專案:Service - server。

建議先下載 Demo 再閱讀,效果會更好:Github_RemoteService_Server

步驟一:建立一個 AIDL 檔

步驟二:在 AIDL 檔中定義需要與 Activity 通訊的方法,然後執行一次編譯(Make Project)

// 在 AIDL_Service1.aidl 中宣告需要與 Activity 通訊的方法
package scut.carson_ho.demo_service;

interface AIDL_Service1 {
    void AIDL_Service();
}

// AIDL 支援的資料型別:
// 1. 八種基本資料型別
// 2. String 與 CharSequence
// 3. List 與 Map(元素必須是 AIDL 支援的型別)
// 4. AIDL 自動產生的介面(需 import)
// 5. 實作 android.os.Parcelable 介面的類別(需 import)

步驟三:在 Service 子類別中實作 AIDL 介面方法,並定義生命週期方法

MyService.java

public class MyService extends Service {

    // 建立 AIDL Stub 類別(Binder 的子類)的實例
    AIDL_Service1.Stub mBinder = new AIDL_Service1.Stub() {
        @Override
        public void AIDL_Service() throws RemoteException {
            System.out.println("用戶端透過 AIDL 與遠端背景成功通訊");
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("執行了 onCreate()");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("執行了 onStartCommand()");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("執行了 onDestroy()");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("執行了 onBind()");
        // 回傳繼承自 Binder 的 Stub 型別物件,這一步非常關鍵
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("執行了 onUnbind()");
        return super.onUnbind(intent);
    }
}

步驟四:在 AndroidManifest.xml 註冊服務並宣告為遠端服務

<service
    android:exported="true"
    android:name=".MyService"
    android:process=":remote">
    <!-- 此 Service 可回應 action 為 scut.carson_ho.service_server.AIDL_Service1 的 Intent -->
    <!-- action 必須寫成「伺服器端套件名.aidl 檔名」-->
    <intent-filter>
        <action android:name="scut.carson_ho.service_server.AIDL_Service1" />
    </intent-filter>
</service>

至此,伺服器端(遠端 Service)就完成了。

4.2 用戶端(Client)

建立用戶端專案:Service - Client。

同樣建議先下載 Demo:Github_RemoteService_Client

步驟一:把伺服器端的 AIDL 檔整個套件複製到用戶端目錄(Project/app/src/main),然後編譯

切記要原封不動地複製,什麼都不要改!

步驟二:在主版面配置檔中定義「綁定服務」按鈕

MainActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="scut.carson_ho.service_client.MainActivity">

    <Button
        android:id="@+id/bind_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="綁定服務" />
</RelativeLayout>

步驟三:在 MainActivity.java 中完成三件事

使用 Stub.asInterface 取得伺服器端的 Binder;透過 Intent 指定伺服器端服務名稱與套件並完成綁定;依需求呼叫服務提供的介面方法。

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private Button bindService;

    // 定義 AIDL 介面變數
    private AIDL_Service1 mAIDL_Service;

    // 建立 ServiceConnection 匿名類別
    private ServiceConnection connection = new ServiceConnection() {

        // Activity 與 Service 解除關聯時呼叫
        @Override
        public void onServiceDisconnected(ComponentName name) { }

        // Activity 與 Service 建立關聯時呼叫
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 透過 Stub.asInterface() 取得伺服器端回傳的 IBinder 物件
            // 並將其轉換為 mAIDL_Service 介面物件
            mAIDL_Service = AIDL_Service1.Stub.asInterface(service);
            try {
                // 透過該物件呼叫 AIDL 中定義的方法,完成跨行程通訊
                mAIDL_Service.AIDL_Service();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindService = (Button) findViewById(R.id.bind_service);

        bindService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 參數需與伺服器端 action 一致,即「伺服器套件名.aidl 介面檔名」
                Intent intent = new Intent("scut.carson_ho.service_server.AIDL_Service1");

                // Android 5.0 之後無法只靠隱式 Intent 綁定遠端 Service
                // 必須以 setPackage() 明確指定套件名
                intent.setPackage("scut.carson_ho.service_server");

                // 綁定服務
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }
        });
    }
}

4.3 測試結果

從測試結果可以歸納出兩點:

輸出的日誌分別執行在不同行程(看訊息前面的套件名);用戶端成功呼叫了伺服器端 Service 的方法。

也就是說,用戶端與伺服器端確實完成了跨行程通訊。

4.4 Demo 下載

用戶端:Github_RemoteService_Client
伺服器端:Github_RemoteService_Server

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