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

Android BLE 低功耗藍牙開發完全指南

編輯:關於 Android 程式設計

隨著物聯網與智慧穿戴裝置的普及,BLE(低功耗藍牙)已成為行動開發中越來越常見的需求。相比傳統基於 IP 的 Socket 通訊,BLE 有著自己的一套概念與編程模式。本文就從基礎概念講起,並附上完整程式碼,帶你快速上手 BLE 開發。

一、什麼是 BLE

BLE(Bluetooth Low Energy)是一項低成本、短距離、可互操作的無線技術,工作在免授權的 2.4GHz ISM 频段,從設計之初就主打超低功耗。它採用可變的連線間隔(幾毫秒到幾秒不等),並透過極快的連線方式運作:平時裝置處於「非連線」狀態以節省電力,只在必要時才建立連線,並在最短時間內完成通訊後關閉。簡單來說,它就是藍牙的一項新技術,特點是低功耗、連線快,但只適合傳輸小量資料。

二、幾個核心概念

  • GATT(Generic Attribute Profile):連接後讀寫屬性小資料的通用規範,現今所有 BLE 應用 Profile 都基於 GATT。
  • ATT(Attribute Protocol):GATT 的底層協議,針對 BLE 做了優化,每個屬性都有唯一 UUID,並以 characteristics 與 services 的形式傳輸。
  • Characteristic:可理解為一種資料型別,包含一個 value 與零到多個描述(Descriptor)。
  • Descriptor:對 Characteristic 的描述,例如範圍、計量單位等。
  • Service:Characteristic 的集合。例如一個名為「Heart Rate Monitor」的 Service,可能包含多個 Characteristic。

請牢記這個層級關係:一個 BLE 裝置可以有多個 Service,一個 Service 可以有多個 Characteristic,一個 Characteristic 有一個 Value 與多個 Descriptor,而一個 Descriptor 包含一個 Value。

三、關鍵 API

  • BluetoothGatt:繼承自 BluetoothProfile,用來連線裝置(connect)、發現服務(discoverServices),並透過 BluetoothGattCallback 回傳結果。
  • BluetoothGattCharacteristic / BluetoothGattDescriptor / BluetoothGattService:分別對應上面的資料型別、描述與服務集合。
  • BluetoothManager:用來取得 BluetoothAdapter。
    BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
  • BluetoothAdapter:一部 Android 裝置只有一個,透過 manager 取得。
    BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
  • BluetoothGattCallback:核心回調類,包含 onConnectionStateChange、onCharacteristicRead、onCharacteristicWrite 等方法,依需求實作即可。

各操作與回調的對應關係如下:setCharacteristicNotification 對應 onCharacteristicChanged;readCharacteristic 對應 onCharacteristicRead;writeCharacteristic 對應 onCharacteristicWrite;連線/斷線對應 onConnectionStateChange;discoverServices 對應 onServicesDiscovered,以此類推。

四、實作程式碼

整體流程是:進入 BLEActivity 掃描裝置,選擇目標裝置點擊後啟動 BLEService,由它建立 GATT 連線、依 UUID 取得對應的 Service 與 Characteristic,隨後即可讀寫資料。BLEService 對外提供了三個介面:self() 取得服務實例、writeToBLE(byte[]) 寫入資料、readFromBLE() 讀取資料。

AndroidManifest.xml 權限宣告

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />

BLEActivity.java(掃描與選擇裝置)

關鍵在於 checkBluetooth() 先判斷是否支援 BLE,接著在 onResume 中啟動掃描,並透過 LeScanCallback 把掃描到的裝置加入清單;使用者點擊項目後,儲存裝置位址並啟動 BLEService:

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

BLEService.java(建立連線與讀寫)

在 onServicesDiscovered 回調中取得目標 Service 與 Characteristic,開啟通知後即可讀寫:

public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        BluetoothGattService mGattService = mBluetoothGatt.getService(SampleGattAttributes.UUID_SERVICE);
        mCharacteristic = mGattService.getCharacteristic(SampleGattAttributes.UUID_CHARACTERISTIC);
        setCharacteristicNotification(mCharacteristic, true);
    }
}

public boolean wirteToBLE(byte[] value) {
    mCharacteristic.setValue(value);
    return mBluetoothGatt.writeCharacteristic(mCharacteristic);
}

public byte[] readFromBLE() {
    if (mBluetoothGatt.readCharacteristic(mCharacteristic)) {
        return mCharacteristic.getValue();
    }
    return null;
}

五、小結

BLE 開發真正的重點不在於程式碼本身,而在於理解它的工作模式與編程步驟。工作模式就是「中心裝置與周邊裝置」以及 GATT/ATT 通訊;編程步驟則可歸納為:準備(加權限、判斷支援、開啟藍牙)→ 掃描裝置 → 建立連線 → 列舉服務 → 開始讀寫通訊 → 關閉連線。把這條主線記牢,BLE 開發就不再難了。

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