萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android BLE 通信實戰:GATT 服務發現、特徵讀寫與通知訂閱全流程

BLE 架構速覽

  • Service (服務):功能模塊集合,由 UUID 標識(16-bit 標準 / 128-bit 自定義)。
  • Characteristic (特徵):數據傳輸單元,含 Value + Descriptors,屬性決定權限(READ/WRITE/NOTIFY/INDICATE)。
  • Descriptor (描述符):特徵元數據,如 Client Characteristic Configuration (0x2902) 啟用通知/指示。

手機 (Central/GATT Client) ↔ 設備 (Peripheral/GATT Server)。

核心流程

  1. 掃描:BluetoothLeScanner.startScan(filters, settings, callback)
  2. 連接:device.connectGatt(context, autoConnect, callback) → BluetoothGatt
  3. 發現服務:gatt.discoverServices() → onServicesDiscovered()
  4. 遍歷服務/特徵/描述符:匹配目標 UUID
  5. 讀/寫/啟用通知:gatt.readCharacteristic() / writeCharacteristic() / setCharacteristicNotification() + 寫入 CCCD
  6. 回調處理:onCharacteristicRead/Write/Changed

完整掃描連接示例 (簡化版)

public class BleScanner {
    private BluetoothLeScanner scanner;
    private BluetoothGatt gatt;
    private final String TARGET_SERVICE_UUID = "0000ffe0-0000-1000-8000-00805f9b34fb";
    private final String TARGET_CHAR_UUID = "0000ffe1-0000-1000-8000-00805f9b34fb";

    public void startScan(Context ctx) {
        BluetoothManager bm = (BluetoothManager) ctx.getSystemService(Context.BLUETOOTH_SERVICE);
        scanner = bm.getAdapter().getBluetoothLeScanner();
        scanner.startScan(buildScanCallback());
    }

    private ScanCallback buildScanCallback() {
        return new ScanCallback() {
            @Override public void onScanResult(int callbackType, ScanResult result) {
                BluetoothDevice device = result.getDevice();
                if (device.getName() != null && device.getName().contains("BLE")) {
                    scanner.stopScan(this);
                    connect(device);
                }
            }
        };
    }

    private void connect(BluetoothDevice device) {
        gatt = device.connectGatt(context, false, new BluetoothGattCallback() {
            @Override public void onConnectionStateChange(BluetoothGatt g, int status, int newState) {
                if (newState == BluetoothProfile.STATE_CONNECTED) g.discoverServices();
                else if (newState == BluetoothProfile.STATE_DISCONNECTED) { /* 重連邏輯 */ }
            }
            @Override public void onServicesDiscovered(BluetoothGatt g, int status) {
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    enumerateAndSetup(g);
                }
            }
            @Override public void onCharacteristicRead(BluetoothGatt g, BluetoothGattCharacteristic c, int status) {
                if (status == BluetoothGatt.GATT_SUCCESS) Log.d(TAG, "Read: " + bytesToHex(c.getValue()));
            }
            @Override public void onCharacteristicWrite(BluetoothGatt g, BluetoothGattCharacteristic c, int status) {
                Log.d(TAG, "Write status: " + status);
            }
            @Override public void onCharacteristicChanged(BluetoothGatt g, BluetoothGattCharacteristic c) {
                Log.d(TAG, "Notify: " + bytesToHex(c.getValue()));
            }
        });
    }

    private void enumerateAndSetup(BluetoothGatt g) {
        for (BluetoothGattService svc : g.getServices()) {
            Log.d(TAG, "Service: " + svc.getUuid() + " type:" + (svc.getType()==BluetoothGattService.SERVICE_TYPE_PRIMARY?"PRIMARY":"SECONDARY"));
            for (BluetoothGattCharacteristic ch : svc.getCharacteristics()) {
                Log.d(TAG, "  Char: " + ch.getUuid() + " prop:0x" + Integer.toHexString(ch.getProperties()) + " perm:0x" + Integer.toHexString(ch.getPermissions()));
                if (ch.getUuid().toString().equalsIgnoreCase(TARGET_CHAR_UUID)) {
                    // 1. 讀取初始值
                    g.readCharacteristic(ch);
                    // 2. 啟用通知
                    g.setCharacteristicNotification(ch, true);
                    BluetoothGattDescriptor cccd = ch.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
                    if (cccd != null) {
                        cccd.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                        g.writeDescriptor(cccd);
                    }
                    // 3. 寫入測試數據
                    ch.setValue("send data->".getBytes());
                    g.writeCharacteristic(ch);
                }
                for (BluetoothGattDescriptor desc : ch.getDescriptors()) {
                    Log.d(TAG, "    Desc: " + desc.getUuid() + " perm:0x" + Integer.toHexString(desc.getPermissions()));
                }
            }
        }
    }

    // 特徵屬性位掩碼解析工具
    public static String parseProperties(int prop) {
        List list = new ArrayList<>();
        if ((prop & BluetoothGattCharacteristic.PROPERTY_READ) != 0) list.add("READ");
        if ((prop & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0) list.add("WRITE");
        if ((prop & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0) list.add("WRITE_NO_RSP");
        if ((prop & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) list.add("NOTIFY");
        if ((prop & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) list.add("INDICATE");
        return TextUtils.join("|", list);
    }
}

關鍵日誌解讀 (對應文章 Log)

  • PROPERTY: READ|WRITE_NO_RESPONSE|NOTIFY → 支持無響應寫入(高吞吐) + 服務端主動推送。
  • onCharRead ... -> 00 → 讀取特徵初始值 0x00。
  • onCharWrite ... -> send data to phone → 設備主動通知數據 (NOTIFY)。

避坑指南

  • Android 6.0+ 需動態權限:ACCESS_FINE_LOCATION 或 BLUETOOTH_SCAN/CONNECT (Android 12+)。
  • 連接參數:connectGatt(autoConnect=false) 主動連接;true 為後台自動重連。
  • 線程安全:所有 GATT 操作需串行(上一個操作回調返回後再發起下一個),否則返回 false。
  • WRITE_NO_RESPONSE 不保證送達,關鍵數據用 WRITE (確認應答)。
  • MTU 協商:gatt.requestMtu(247) 提高單包傳輸效率 (默認 20 字節)。
  • 斷開釋放:gatt.close() 並在 onDestroy() 執行。

現代庫推薦

  • RxBle (RxJava) — 響應式鏈式調用,自動處理串行隊列。
  • Android BLE Library (Kotlin Coroutines/Flow) — 結構化併發、生命周期感知。
  • Nordic Semiconductor nRF Connect SDK — 專業調試與開發參考。
copyright © 萬盛學電腦網 all rights reserved