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

Android BLE 藍牙 4.0 開發入門總結(一)

編輯:關於 Android 程式設計

本文介紹 Android BLE(藍牙 4.0)開發。使用前提是:API level ≥ 18,且手機硬體支援藍牙 4.0;若系統版本低於 4.3,則無法使用這套 API。

官方 Demo 值得先跑一遍:Android 4.3 以上搭配支援 BLE 的手機,即可實現掃描、配對、連接、發現服務與特徵值、斷開連接等完整流程。

一、API 與核心概念

1. BluetoothGatt

繼承自 BluetoothProfile,是 BLE 數據收發的通用規範。透過它可以連接設備(connect)、發現服務(discoverServices),並把結果回送到 BluetoothGattCallback。

2. BluetoothGattCharacteristic

相當於一個數據類型,包含一個 value 與 0~n 個描述(BluetoothGattDescriptor)。

3. BluetoothGattDescriptor

描述符,用來補充說明 Characteristic 的屬性,例如取值範圍、計量單位等。

4. BluetoothGattService

服務,是若干 Characteristic 的集合。

5. BluetoothManager 與 BluetoothAdapter

BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
// 一個 Android 系統只有一個 BluetoothAdapter
BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();

6. BluetoothGattCallback

所有對設備的操作結果都透過這個回呼返回。特別提醒:必須先連接上設備才會有回調;若一直沒有回調,先確認是否真的連接成功。

private BluetoothGattCallback GattCallback = new BluetoothGattCallback() {
    // 共 9 個方法,用到哪些就實作哪些
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {}
    public void onCharacteristicWrite(BluetoothGatt gatt,
                                      BluetoothGattCharacteristic characteristic, int status) {}
};

BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
BluetoothGatt gatt = device.connectGatt(this, false, mGattCallback);

各操作與回呼的對應關係:

  • setCharacteristicNotification() → onCharacteristicChanged
  • readCharacteristic() → onCharacteristicRead
  • writeCharacteristic() → onCharacteristicWrite
  • 連接/斷開藍牙 → onConnectionStateChange
  • readDescriptor() → onDescriptorRead
  • writeDescriptor() → onDescriptorWrite
  • readRemoteRssi() → onReadRemoteRssi
  • executeReliableWrite() → onReliableWriteCompleted
  • discoverServices() → onServicesDiscovered

7. BluetoothDevice

掃描後發現的可連接設備物件,也可用來取得已配對/已連接的設備。

二、開啟藍牙權限

<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="true"/>

如果把 android.hardware.bluetooth_le 設為 false,程式也能安裝在不支援 BLE 的設備上,此時用下面的程式碼判斷即可:

if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    Toast.makeText(this, "設備不支持藍牙4.0", Toast.LENGTH_SHORT).show();
    finish();
}

三、開啟與關閉藍牙

1. 使用系統預設對話框開啟(使用者可確認,體驗較好)

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

2. 後台直接開啟(不做任何提示,也常用於自定義對話框的場景)

mBluetoothAdapter.enable();

3. 後台關閉

mBluetoothAdapter.disable();

四、後續步驟

掃描設備(startScan 搭配 BluetoothAdapter.LeScanCallback)、連接設備、讀寫特徵值、以及斷開連接的實作,直接對照官方 Demo 會更清晰,這裡不再贅述。

實務提醒:Android 6.0(API 23)之後,掃描 BLE 需要動態申請位置權限,且 startScan 已被 ScanBuilder/BluetoothLeScanner 取代;Android 12 以上還需要 BLUETOOTH_SCAN、BLUETOOTH_CONNECT 等新權限。若要做跨版本相容,建議針對 API 級別分別處理。

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