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

Android BLE 開發筆記:掃描、連線與廣播數據解析

編輯:關於 Android 程式設計

前言

Android BLE 開發涉及掃描、GATT 連線、服務探索與廣播數據解析。本文整理基礎概念與操作流程,適合剛接觸低功耗藍牙的開發者。

藍牙分類

常見名詞包括 Bluetooth Smart Ready、Bluetooth Smart 與標準 Bluetooth。Smart Ready 多指雙模裝置,可與傳統藍牙與 BLE 通訊;Smart 則常指單模低功耗裝置。

BLE 名詞

BLE 是 Bluetooth Low Energy,源自 Wibree,主打低功耗與較長有效距離。Android 4.3 之後才支援 BLE,因此並非所有藍牙手機都支援。

核心概念

GAP 管理裝置連接與廣播;GATT 是屬性資料通用規範;ATT 是 GATT 的基礎協定。Characteristic 是資料型別,Descriptor 描述其屬性,Service 則是 Characteristic 的集合,UUID 是唯一識別碼。

Android BLE API

常用類別包括 BluetoothManager、BluetoothAdapter、BluetoothDevice、BluetoothGatt、BluetoothGattService、BluetoothGattCharacteristic、BluetoothGattDescriptor 與 BluetoothGattCallback。

開啟與掃描

使用前需確認裝置支援 BLE 且藍牙已開啟。掃描時可使用 startLeScan,並在 onLeScan 中取得裝置、rssi 與 scanRecord。找到目標後應停止掃描,避免耗電。

連線與資料傳輸

透過 connectGatt 建立連線,再呼叫 discoverServices 探索服務。可讀寫 Characteristic、開啟 notification、讀取 RSSI 等,結果會回呼到 BluetoothGattCallback。

廣播包解析

掃描資料分為 Advertising Data 與 Scan Response,每個 AD Structure 由長度、AD Type 與 AD Data 組成。AD Type 決定資料意義,例如裝置名稱、UUID、外觀、廠商自訂資料等。

小結

BLE 開發的關鍵在於理解 GATT 架構、掃描回呼與廣播封包格式。掌握這些基礎後,再依裝置協議實作通知、讀寫與狀態同步,會更順利。

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