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

Android BLE 開發:封裝一個通用藍牙工具類,讀取小米手環步數

編輯:關於 Android 程式設計

物聯網正熱,小米手環這類可穿戴設備幾乎人手一只。本文示範如何封裝一套通用的 BLE(Bluetooth Low Energy)工具類,並用它讀取小米手環的運動數據。

一、為什麼要自己封裝

Android 原生 BLE 相關 API 分散在 BluetoothManager、BluetoothAdapter、BluetoothDevice、BluetoothGatt 幾個類裡,回呼層層嵌套。把這些細節收攏到一個單例工具類中,業務層只需要關心「開始掃描」「拿到設備」「建立連線」三件事即可。

二、工具類 UniversalBluetoothLE.java

package com.zsl.bluetoothdemo.ble;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;

import java.util.ArrayList;
import java.util.List;

/**
 * 藍牙低功耗(BLE)通用工具類
 */
public class UniversalBluetoothLE {

    public static UniversalBluetoothLE universalBluetoothLE;

    private Context context;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager bluetoothManager;

    /** 請求開啟藍牙的 requestCode */
    public static final int REQUEST_ENABLE_BLUETOOTH = 10010;
    /** 是否正在掃描 */
    private boolean mScanning;
    /** 掃描時長:10 秒 */
    private static final long SCAN_PERIOD = 10000;

    private BluetoothAdapter.LeScanCallback leScanCallback;
    private List<BluetoothDevice> bluetoothDeviceList = new ArrayList<>();
    private Handler mHandler = new Handler();
    private LeScanListenter leScanListenter;

    private UniversalBluetoothLE(Context context) {
        this.context = context;
        this.bluetoothManager = (BluetoothManager)
                context.getSystemService(Context.BLUETOOTH_SERVICE);
        this.mBluetoothAdapter = bluetoothManager.getAdapter();

        leScanCallback = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                if (!bluetoothDeviceList.contains(device)) {
                    bluetoothDeviceList.add(device);
                }
                // 把最新列表回呼給上層
                leScanListenter.leScanCallBack(bluetoothDeviceList);
            }
        };
    }

    /** 取得單例 */
    public static UniversalBluetoothLE inistance(Context context) {
        if (universalBluetoothLE == null) {
            universalBluetoothLE = new UniversalBluetoothLE(context);
        }
        return universalBluetoothLE;
    }

    /** 檢查藍牙狀態,未開啟則跳轉系統開啟頁 */
    public void openBbletooth() {
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            enableIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(enableIntent);
        }
    }

    /** 開始或停止掃描 */
    private void scanLeDevice(final boolean enable) {
        if (enable && !mScanning) {
            // 超時自動停止,避免持續耗電
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    mBluetoothAdapter.stopLeScan(leScanCallback);
                }
            }, SCAN_PERIOD);
            mScanning = true;
            mBluetoothAdapter.startLeScan(leScanCallback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(leScanCallback);
        }
    }

    /** 對外暴露:開始搜索 */
    public void startScanLeDevice(final LeScanListenter listener) {
        bluetoothDeviceList.clear();
        this.leScanListenter = listener;
        scanLeDevice(true);
    }

    /** 對外暴露:停止搜索 */
    public void stopScanLeDevice() {
        if (leScanCallback == null) return;
        scanLeDevice(false);
    }

    /** 掃描結果回呼 */
    public interface LeScanListenter {
        void leScanCallBack(List<BluetoothDevice> bluetoothDeviceList);
    }

    /** 建立 GATT 連線 */
    public BluetoothGatt getConnectGatt(BluetoothDevice device, boolean autoConnect,
                                        BluetoothGattCallback callback) {
        return device.connectGatt(context, autoConnect, callback);
    }
}

三、調用流程

1. 在 onCreate 中初始化

universalBluetoothLE = UniversalBluetoothLE.inistance(MainActivity.this);

2. 檢查並請求開啟藍牙

universalBluetoothLE.openBbletooth();

3. 開始掃描,取得設備列表

universalBluetoothLE.startScanLeDevice(new UniversalBluetoothLE.LeScanListenter() {
    @Override
    public void leScanCallBack(List<BluetoothDevice> list) {
        // 更新列表 UI,通常再結合 rssi 做信號排序
    }
});

4. 連上目標設備

mBluetoothGatt = universalBluetoothLE.getConnectGatt(device, true, mGattCallback);
mBluetoothGatt.connect();

5. 實作 BluetoothGattCallback

在 onConnectionStateChange 中處理連線狀態,連上後呼叫 discoverServices();在 onServicesDiscovered 中取得目標 Service 與 Characteristic,打開 notify 並等待 onCharacteristicChanged 回呼,就能拿到手環上報的資料。

四、實測結果

按照上面的流程,小米手環的計步數據可以穩定讀出:

五、幾個實務提醒

Android 6.0 以後掃描需要定位權限與 ACCESS_COARSE_LOCATION,Android 12 以上則要改用 BLUETOOTH_SCAN / BLUETOOTH_CONNECT;startLeScan 系列 API 在 API 31 已標記為 deprecated,新專案建議改用 BluetoothLeScanner 搭配 ScanFilter,掃描效率與可控性都更好。此外 BLE 特征值多为十六位元字节流,解析前务必向设备厂商确认协议文档中的字节序与单位换算规则。

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