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

Android BLE 多連線實作:同時管理遙控器與耳機的 GATT 通道

編輯:關於 Android 程式設計

在物聯網與穿戴裝置的應用場景裡,手機往往需要「一心二用」——同時連上兩台以上的低功耗藍牙(BLE)裝置。本文以一個實際案例為主軸:手機端需要同時維持與智慧遙控器、藍牙耳機的連線,雙方各自採用不同的 Service UUID,並在其中一台上做資料讀寫。我們會從掃描、連線、資料收發到資源釋放,完整拆解整個流程。

整體架構:Service 負責掃描,Manager 負責連線

常見的做法是把「週期性掃描」的邏輯封裝在一個常駐的 Service 裡,再讓一個單例的 RMTBle 管理器負責真正建立 GATT 連線。這樣做的好處是職責分明:Service 只管生命週期與定時喚醒,管理器則專注於連線狀態與資料通道。

掃描服務的核心,是用 HandlerThread 開一條工作 thread,透過 Runnable 每隔一段時間重新觸發一次掃描,並在掃描啟動後的 SCAN_PERIOD(這裡設為 8 秒)自動停止,避免藍牙晶片長時間高負載運作:

public class RMTBleService extends Service {
    private final long SCAN_PERIOD = 8000; // 8 秒
    private Handler mHandler;
    private HandlerThread handlerThread;
    private boolean mStop = false;

    @Override
    public void onCreate() {
        super.onCreate();
        mStop = false;
        handlerThread = new HandlerThread("ble-scan");
        handlerThread.start();
        mHandler = new Handler(handlerThread.getLooper());
        mHandler.post(mRunnable);
    }

    private Runnable mRunnable = new Runnable() {
        public void run() {
            if (mStop) return;
            scanBleDevice(true);
            mHandler.postDelayed(this, 8500); // 掃描間隔略大於掃描時長
        }
    };

    private Runnable mStopLeScanRunable = new Runnable() {
        public void run() {
            if (mStop) return;
            RMTBle.getInstance(RMTBleService.this).stopLeScan();
        }
    };

    public void scanBleDevice(boolean enable) {
        if (enable) {
            mHandler.postDelayed(mStopLeScanRunable, SCAN_PERIOD);
            RMTBle.getInstance(RMTBleService.this).startLeScan();
        } else {
            RMTBle.getInstance(RMTBleService.this).stopLeScan();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mStop = true;
        mHandler.removeCallbacks(mRunnable);
        mHandler.removeCallbacks(mStopLeScanRunable);
        RMTBle.getInstance(this).destroy();
    }
}

用 UUID 過濾掃描結果

BLE 的 Advertisement 封包裡通常帶有 Service UUID,我們可以在掃描回呼中把這段位元組擷取出來,只針對感興趣的裝置建立連線。由於 BLE 的 UUID 在廣播封包中是以小端序(little-endian)存放的,因此必須先還原位元組順序,再重新組回標準的 UUID 字串格式:

// 從 scanRecord 中擷取並還原 128-bit 的 Service UUID
private UUID guuid_record(byte[] scanRecord) {
    final int serviceOffset = 5;
    try {
        byte[] service = ArrayUtils.subarray(scanRecord, serviceOffset, serviceOffset + 16);
        ArrayUtils.reverse(service);
        String id = bytesToHex(service);
        String realId = id.substring(0, 8) + "-" + id.substring(8, 12) + "-"
                + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20);
        return UUID.fromString(realId);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

在 onLeScan 回呼中,只要比對到的 UUID 命中了遙控器或耳機的目標,就呼叫 connect()。這裡用一個 count 計數器限制最多隻連兩台,並用 lastAddress 避免對同一裝置重複連線:

private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
        String address = device.getAddress();
        if (count < 2) {
            UUID uuid = guuid_record(scanRecord);
            if (uuid != null && (uuid.equals(keyUUID) || uuid.equals(earUUID))) {
                if (!address.equalsIgnoreCase(lastAddress)) {
                    if (connect(device, uuid)) {
                        lastAddress = address;
                        count++;
                    }
                }
            }
        }
    }
};

為不同裝置維護獨立的 GATT 連線

多連線的關鍵在於:每台裝置都各自持有一個 BluetoothGatt 物件,並搭配各自的 BluetoothGattCallback。管理器用 bGettKeyboard 與 bGettHearset 兩個欄位分別持有遙控器與耳機的連線,並依 UUID 前綴決定要走哪一條通道:

public boolean connect(BluetoothDevice device, UUID uuid) {
    String connectAddress = device.getAddress();
    final BluetoothDevice deviceTemp = mBluetoothAdapter.getRemoteDevice(connectAddress);

    // 遙控器:UUID 以 678fea09 開頭
    if (uuid.toString().startsWith("678fea09")) {
        bGettKeyboard = deviceTemp.connectGatt(mContext, false, gattKeyboard);
        if (bGettKeyboard != null) {
            lastAddress = connectAddress;
            keyStatus = true;
            CommonMethods.saveBooleanSharedParameter(mContext, Constants.BLE_KEY_STATUS, keyStatus);
            return true;
        }
    }
    // 耳機:UUID 以 00006678 開頭
    if (uuid.toString().startsWith("00006678")) {
        bGettHearset = deviceTemp.connectGatt(mContext, false, gettHearset);
        if (bGettHearset != null) {
            lastAddress = connectAddress;
            earStatus = true;
            CommonMethods.saveBooleanSharedParameter(mContext, Constants.BLE_EAR_STATUS, earStatus);
            return true;
        }
    }
    return false;
}

連線成功後,在 onConnectionStateChange 中呼叫 discoverServices(),並於 onServicesDiscovered 裡找出目標 Characteristic,啟用通知(notification)。值得注意的是,一旦某台裝置斷線,務必把 lastAddress 清空並將計數器減一,否則後續將無法重新連上:

private BluetoothGattCallback gettHearset = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            bGettHearset.discoverServices();
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            lastAddress = "";   // 斷線後清空,才能重連
            count--;            // 連線數減一
            bGettHearset.close();
            bGettHearset = null;
            CommonMethods.saveBooleanSharedParameter(mContext, Constants.BLE_EAR_STATUS, false);
        }
    }
    // onServicesDiscovered / onCharacteristicChanged 略
};

資料收發:封包拆分與緩衝

由於 BLE 單次寫入的負載有限(此案例為 16 位元組),送資料時必須先按 MAX_PACKET_SIZE 切片,逐段寫入 Characteristic,並採用 WRITE_TYPE_NO_RESPONSE 以提升吞吐:

public int send(byte[] data) {
    if (bGettHearset == null) return 0;
    BluetoothGattService service = bGettHearset.getService(earUUID);
    if (service == null) return 0;
    BluetoothGattCharacteristic ch = service.getCharacteristic(earWriteUUID);
    if (ch == null) return 0;

    int loop = data.length / MAX_PACKET_SIZE;
    byte[] tmp = new byte[MAX_PACKET_SIZE];
    for (int i = 0; i < loop; i++) {
        System.arraycopy(data, i * MAX_PACKET_SIZE, tmp, 0, MAX_PACKET_SIZE);
        ch.setValue(tmp);
        ch.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
        bGettHearset.writeCharacteristic(ch);
    }
    if (data.length % MAX_PACKET_SIZE > 0) {
        System.arraycopy(data, loop * MAX_PACKET_SIZE, tmp, 0, data.length % MAX_PACKET_SIZE);
        ch.setValue(tmp);
        ch.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
        bGettHearset.writeCharacteristic(ch);
    }
    return data.length;
}

接收端則用一塊 MAX_BUFFER_SIZE 的緩衝區暫存資料,並以 synchronized 的 handle_buffer() 方法保證讀寫的一致性,避免多 thread 競爭時出現資料錯亂。

重點回顧

歸納起來,BLE 多連線的實作要點有幾個:一是用常駐 Service 週期性掃描、定時停止以節電;二是從廣播封包中正確還原 UUID 做裝置過濾;三是為每台裝置維護獨立的 BluetoothGatt 與 callback;四是斷線時務必清理狀態以便重連;五是送資料前先做封包切片。掌握這幾點,就能穩定地同時管理多台下功耗藍牙裝置。

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