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

Android BLE 開發完整指南:GATT 架構、裝置掃描、讀寫特性與通知

編輯:關於 Android 程式設計

從 Android 4.3(API 18)開始,平台正式為 Bluetooth Low Energy(以下簡稱 BLE)的核心能力提供了支援:App 可以掃描並發現裝置、查詢服務、讀寫特性。與傳統藍牙相比,BLE 最大的設計取向就是低功耗,也正因如此,它特別適合與距離感測器、心率帶、健身設備這類長期配戴、電力吃緊的裝置溝通。

關鍵術語與概念

GATT(Generic Attribute Profile):一個通用規範,定義了 BLE 連結上如何收發被稱為 attribute 的資料塊。目前幾乎所有低功耗應用都建立在 GATT 之上。藍牙 SIG 為低功耗裝置定義了大量 profile,用來描述裝置在特定情境下的行為;一個裝置可以同時實作多個 profile,例如同時具備心率偵測與電池電量回報。

ATT(Attribute Protocol):GATT 建立在 ATT 之上,因此也常被合稱為 GATT/ATT。ATT 針對 BLE 做了精簡優化,盡可能壓縮每個封包的位元組數。每個屬性由 UUID 唯一標識,UUID 以 128 位元表示;屬性則被組織為 characteristics 與 services 兩個層級。

Characteristic(特性):包含一個值以及 0 到多個 descriptors,用來描述這個值。可以把 Characteristic 理解為一個「型別」,是實際承載資料的最小單位。

Descriptor(描述符):定義並描述 Characteristic 的值。例如它可以標註這是一個唯讀欄位、限制某個數值可接受的範圍,或指定測量單位。

Service(服務):一組 Characteristic 的集合。比方說一個名為「心率偵測」的 Service,底下會包含「心率測量值」「心率感測器位置」等 Characteristic。

角色與責任

Central 與 Peripheral:這組角色描述的是連結本身。中央裝置(Central)負責掃描、尋找廣播;外圍裝置(Peripheral)負責發送廣播。兩台都只支援同一種角色的裝置無法互相通訊。

GATT Server 與 GATT Client:連結建立之後,兩方才開始互相傳輸 GATT 資料。誰扮演伺服器,取決於資料流向。以手機搭配活動追蹤器為例:手機是 Central,追蹤器是 Peripheral;追蹤器要把感測器資料送到手機,它就是 GATT Server;若追蹤器需要接收手機下發的設定,手機就成為 GATT Server。

在官方範例裡,跑在 Android 上的 App 是 GATT Client,它向支援心率 profile 的心率帶(GATT Server)取資料。當然,Android 也可以反過來擔任 GATT Server,如需實作請參考 BluetoothGattServer。

權限宣告

要使用藍牙功能,必須在 manifest 中宣告 BLUETOOTH 權限,用於請求連結、接收連結與傳輸資料。如果需要初始化裝置或操作藍牙設定(例如開啟/關閉藍牙),還必須加上 BLUETOOTH_ADMIN 權限;注意宣告 ADMIN 時,BLUETOOTH 也必須同時存在。

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

若你的 App 只支援 BLE 裝置,建議再補上:

<uses-feature android:name="android.hardware.bluetooth_le" android:required="true" />

如果希望 App 也能安裝在不支援 BLE 的機型上,就把 required 設為 false,並在執行期動態判斷:

if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
    finish();
}

初始化 BLE

與 BLE 通訊之前,先確認兩件事:裝置是否支援 BLE、藍牙是否已開啟。第一步是取得 BluetoothAdapter,它是整個系統唯一的藍牙無線電代表:

final BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

BluetoothManager 是 API 18 才引入的入口,請勿再用舊寫法。第二步是確認藍牙已啟用,若未開啟,可以跳系統對話框引導使用者開啟,而不必離開 App:

if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

掃描 BLE 裝置

掃描使用 startLeScan(),並實作 BluetoothAdapter.LeScanCallback 接收結果。掃描是耗電大戶,請守住兩條紀律:找到目標就立刻停止掃描;不要無限循環掃描,務必設定逾時。剛才還在範圍內的裝置,下一刻可能已經走遠,繼續掃描只是白耗電力。

private Handler mHandler;
private boolean mScanning;
private static final long SCAN_PERIOD = 10000; // 10 秒後自動停止

private void scanLeDevice(final boolean enable) {
    if (enable) {
        mHandler.postDelayed(new Runnable() {
            @Override public void run() {
                mScanning = false;
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            }
        }, SCAN_PERIOD);
        mScanning = true;
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    } else {
        mScanning = false;
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
    }
}

private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
        runOnUiThread(new Runnable() {
            @Override public void run() {
                mLeDeviceListAdapter.addDevice(device);
                mLeDeviceListAdapter.notifyDataSetChanged();
            }
        });
    }
};

如果只關心特定服務,可以使用 startLeScan(UUID[], LeScanCallback) 過濾,避免無關裝置干擾。另外要記住:BLE 裝置與傳統藍牙裝置無法同時掃描。

連線到 GATT Server

與 BLE 互動的第一步是建立連結,呼叫 connectGatt(),它需要三個參數:Context、autoConnect(是否可用時自動連線)與 BluetoothGattCallback。

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

成功後會拿到一個 BluetoothGatt 實例,後續所有 GATT Client 操作都透過它進行;而 BluetoothGattCallback 則負責把結果回傳給你,包括連結狀態變化、服務探索結果、特性讀取結果等。

實務上通常會把這些邏輯收進一個 Service,讓連結不因 Activity 切換而中斷,並用廣播把狀態與資料送給 UI 層:

public class BluetoothLeService extends Service {
    private BluetoothGatt mBluetoothGatt;
    private int mConnectionState = STATE_DISCONNECTED;

    public final static String ACTION_GATT_CONNECTED = "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED = "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE = "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA = "com.example.bluetooth.le.EXTRA_DATA";

    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                mConnectionState = STATE_CONNECTED;
                broadcastUpdate(ACTION_GATT_CONNECTED);
                // 連上之後立刻探索服務
                mBluetoothGatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                mConnectionState = STATE_DISCONNECTED;
                broadcastUpdate(ACTION_GATT_DISCONNECTED);
            }
        }

        @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
            }
        }

        @Override public void onCharacteristicRead(BluetoothGatt gatt,
                                                   BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }
        }

        @Override public void onCharacteristicChanged(BluetoothGatt gatt,
                                                      BluetoothGattCharacteristic characteristic) {
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }
    };

    private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
        final Intent intent = new Intent(action);
        // 心率 profile 需依規格解析 flag 與資料格式
        if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
            int flag = characteristic.getProperties();
            int format = (flag & 0x01) != 0
                    ? BluetoothGattCharacteristic.FORMAT_UINT16
                    : BluetoothGattCharacteristic.FORMAT_UINT8;
            int heartRate = characteristic.getIntValue(format, 1);
            intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
        } else {
            final byte[] data = characteristic.getValue();
            if (data != null && data.length > 0) {
                final StringBuilder hex = new StringBuilder(data.length);
                for (byte b : data) hex.append(String.format("%02X ", b));
                intent.putExtra(EXTRA_DATA, new String(data) + "\n" + hex.toString());
            }
        }
        sendBroadcast(intent);
    }
}

Activity 側只需要一個 BroadcastReceiver 接收這些 action,分別更新連線狀態、清畫面、顯示服務清單與資料。這樣切分的好處是:通訊邏輯集中、UI 隨時可重建,也不會因為旋轉螢幕而斷線。

讀取與探索屬性

連結成功並完成服務探索後,就可以遍歷 GATT Services 與 Characteristics,把裝置支援的能力呈現在畫面上。典型做法是外層走訪 Service、內層走訪它的 Characteristic 清單,組成一棵可展開的列表:

private void displayGattServices(List gattServices) {
    if (gattServices == null) return;
    for (BluetoothGattService gattService : gattServices) {
        String uuid = gattService.getUuid().toString();
        // 加入 service 層級的顯示資料
        List gattCharacteristics = gattService.getCharacteristics();
        for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
            String charaUuid = gattCharacteristic.getUuid().toString();
            // 加入 characteristic 層級的顯示資料
        }
    }
}

接收 GATT 通知

若希望裝置在數值變化時主動推給 App,而不是由 App 輪詢,就必須啟用通知。做法是呼叫 setCharacteristicNotification(),並寫入 Client Characteristic Configuration 描述符:

mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
        UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);

啟用之後,只要遠端裝置的該特性發生變化,onCharacteristicChanged() 就會被觸發,把資料送進你的廣播流程。這是 BLE 省電的關鍵:訂閱代替輪詢。

收尾:一定要釋放資源

Client 使用完畢後,請呼叫 close(),讓系統立即回收藍牙資源,否則容易出現連線洩漏與後續重連失敗:

public void close() {
    if (mBluetoothGatt == null) {
        return;
    }
    mBluetoothGatt.close();
    mBluetoothGatt = null;
}

BLE 開發的難點很少在 API 本身,而在於狀態管理與電量紀律:設定掃描逾時、把連線放進 Service、能用通知就不要輪詢。做到這三點,你的 App 才配得上「低功耗」這三個字。

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