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

徹底搞懂 Android AIDL:為什麼需要它,以及怎麼用

編輯:關於 Android 程式設計

一、為什麼要有 AIDL

學任何東西之前,先想清楚它為什麼存在。關於 AIDL,很多人腦中的印象是「可以跨進程呼叫其他應用」。但能做到這件事的技術並不少:

  • 廣播:A 在 Manifest 註冊某個 Action,B 送出該 Action 的廣播,A 就能收到——這算通訊,但是單向的。
  • ContentProvider:透過 URI 把資料暴露給其他應用查詢——這是資料共享,不是行為呼叫。
  • Messenger:Android 官方推出來解決應用間通訊的方案,確實能跨進程。

那 AIDL 存在的意義是什麼?官方文件講得很乾脆:

Note: Using AIDL is necessary only if you allow clients from different applications to access your service for IPC and want to handle multithreading in your service. If you do not need to perform concurrent IPC across different applications, you should create your interface by implementing a Binder or, if you want to perform IPC, but do not need to handle multithreading, implement your interface using a Messenger.

翻譯成白話:只有當你允許來自不同應用程式的用戶端存取你的服務,而且需要處理多執行緒問題時,才必須使用 AIDL。不需要跨應用並發,就用 Binder;需要跨進程但不必處理多執行緒,用 Messenger 就好。

關鍵差異因此非常清楚:AIDL 是為多執行緒、多用戶端並發存取而設計的;Messenger 是單執行緒序列化處理。一句話就說明白了。

二、AIDL 實作三步驟

步驟一:定義 AIDL 檔

// IRemoteService.aidl
package com.example.android;

interface IRemoteService {
    /** 取得服務所在的行程 ID */
    int getPid();

    /** 示範 AIDL 可用的基本型別 */
    void basicTypes(int anInt, long aLong, boolean aBoolean,
                    float aFloat, double aDouble, String aString);
}

存檔之後,Android 編譯器會自動在 gen 目錄下產生 IRemoteService.java。

步驟二:實作服務端

建立 DDService.java,並在 AndroidManifest.xml 註冊,加上對外的 Action:

package com.example.service;

import com.example.android.IRemoteService;

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

public class DDService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("DDService onCreate........ Thread: "
                            + Thread.currentThread().getName());
    }

    @Override
    public IBinder onBind(Intent arg0) {
        System.out.println("DDService onBind");
        return mBinder;
    }

    private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
        public int getPid() {
            System.out.println("Thread: " + Thread.currentThread().getName());
            System.out.println("DDService getPid");
            return Process.myPid();
        }

        public void basicTypes(int anInt, long aLong, boolean aBoolean,
                               float aFloat, double aDouble, String aString) {
            System.out.println("Thread: " + Thread.currentThread().getName());
            System.out.println("basicTypes aDouble: " + aDouble
                    + " anInt: " + anInt
                    + " aBoolean " + aBoolean
                    + " aString " + aString);
        }
    };
}

把服務端跑起來,重點觀察 log 裡的執行緒名稱。

步驟三:實作用戶端

另開一個工程,記得把同一份 AIDL 檔複製進來(它是標準介面定義,兩邊必須一致):

package com.example.aidlclient;

import android.app.Activity;
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.Process;
import android.os.RemoteException;
import android.view.View;

import com.example.android.IRemoteService;

public class MainActivity extends Activity {

    private IRemoteService remoteService;

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

    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) { }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            remoteService = IRemoteService.Stub.asInterface(service);
            try {
                int pid = remoteService.getPid();
                int currentPid = Process.myPid();
                System.out.println("currentPID: " + currentPid + " remotePID: " + pid);
                remoteService.basicTypes(12, 1223L, true, 12.2f, 12.3, "我們的愛,我明白");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            System.out.println("bind success! " + remoteService.toString());
        }
    };

    public void buttonClick(View view) {
        System.out.println("begin bindService");
        Intent intent = new Intent("duanqing.test.aidl");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

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

三、執行結果印證了什麼

點擊用戶端按鈕,觀察兩邊的 log:

  • 服務端 onCreate 跑在 Thread: main——這是服務自己的主執行緒;
  • 用戶端呼叫 getPid() 時,服務端在 Thread: Binder2 中執行;
  • 用戶端呼叫 basicTypes() 時,服務端在 Thread: Binder1 中執行。

兩個請求落在不同執行緒上,這正是 AIDL 的價值所在:它為每個進來的用戶端請求建立執行緒池,讓並發成為可能。若改用 Messenger,這些呼叫會被排成一列依序處理,第二個請求必須等第一個做完。

所以選擇很簡單:需要並發與多執行緒安全,用 AIDL;只是被動接收指令、順序不重要,用 Messenger 更省事。

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