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

深入解析 Android 與藍牙 BLE 的通信機制與實作

編輯:關於 Android 開發

深入解析 Android 與藍牙 BLE 的通信機制與實作

本文以通俗方式解析 Android 與藍牙 BLE(低功耗藍牙)之間的通信原理,並附上完整程式碼。(注意:藍牙 4.0 需 Android 4.3 及以上版本才支援。)

一、BLE 的基本概念

BLE(Bluetooth Low Energy)是藍牙 4.0 核心 profile,主要特點是快速搜索、快速連接、超低功耗保持連接與數據傳輸,缺點是傳輸速率較低,因此常用於可穿戴設備。

BLE 數據傳輸涉及幾個關鍵概念:

  • Profile:可理解為一種規範或標準通信協議,存在於手機中,每個 profile 包含多個 service。
  • Service:一個服務,BLE 從機中包含多個服務(如電量信息、系統服務等),每個 service 包含多個 characteristic。
  • Characteristic(特征值):BLE 主從機通信的核心,可理解為一個標簽,透過它讀取或寫入相關信息。
  • UUID(統一標識碼):service 與 characteristic 都需要唯一的 UUID 進行標識。

通俗來講,app 搜索到 BLE 設備後,會收到設備反饋的信息(如電量),這些信息存在於約定好的 characteristic 對象中;反之,app 也能透過寫入信息到 characteristic 發送給設備,讓設備執行相應動作。這和平常的對象賦值類似,只是方法從 set 變成了 write。

打個比方:characteristic 好比球隊的球員,service 好比球隊名稱,profile 則像國家。要找到某個球員並了解他的信息,需先知道國家、再知道球隊、最後才能找到球員。

二、權限與相關屬性

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

三、初始化藍牙

建議寫在啟動 Activity 中,避免用戶需手動開啟藍牙影響體驗:

private void initBluetooth() {
    BluetoothManager mBluetoothManager = (BluetoothManager) this.getSystemService(Context.BLUETOOTH_SERVICE);
    if (mBluetoothManager != null) {
        BluetoothAdapter mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter != null) {
            if (!mBluetoothAdapter.isEnabled()) {
                mBluetoothAdapter.enable(); // 打開藍牙
            }
        }
    }
}

四、獲取本地 BLE 對象並搜索設備

把 BLE 通信相關程式碼集中到一個工具類 BleManager 中,便於維護與調用。透過 BluetoothAdapter.startLeScan() 搜索設備,並以回調 LeScanCallback 處理搜索結果:

private BluetoothAdapter mBluetoothAdapter;
private BluetoothDevice mBluetoothDevice;
private BluetoothGatt mBluetoothGatt;
private boolean isScanning = false;

private BleManager(Context context) {
    this.mContext = context;
    BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
    if (bluetoothManager == null) {
        return;
    }
    mBluetoothAdapter = bluetoothManager.getAdapter();
}

public void startLeScan() {
    if (mBluetoothAdapter == null) return;
    if (isScanning) return;
    isScanning = true;
    mBluetoothAdapter.startLeScan(mLeScanCallback); // 回調函數
    mHandler.sendEmptyMessageDelayed(STOP_LESCAN, 10000); // 10 秒後停止搜索
}

private LeScanCallback mLeScanCallback = new LeScanCallback() {
    @Override
    public void onLeScan(BluetoothDevice device, int arg1, byte[] arg2) {
        if (device.getName() == null) return;
        if (device.getName().contains("Ble_Name")) { // 判斷是否為目標設備
            mBluetoothDevice = device; // 獲取周邊設備
            stopLeScan(); // 找到後立即停止掃描,避免耗電
            connect();    // 連接
        }
    }
};

五、連接設備

搜索到設備後透過 connectGatt() 建立 GATT 連接(Android 作為 client 端),並以 BluetoothGattCallback 處理連接狀態與服務發現:

public boolean connect() {
    if (mBluetoothDevice == null) return false;
    // Android 作為 client 端,連接 GATT Server
    mBluetoothGatt = mBluetoothDevice.connectGatt(mContext, false, mGattCallback);
    return mBluetoothGatt != null && mBluetoothGatt.connect();
}

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            gatt.discoverServices(); // 連接成功後發現服務
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            // 處理斷開連接
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            getBatteryLevel(); // 獲取電量
        }
    }
    // onCharacteristicRead / onCharacteristicChanged / onCharacteristicWrite 等回調省略
};

六、獲取服務與特征值

// 獲取服務
public BluetoothGattService getService(UUID uuid) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) return null;
    return mBluetoothGatt.getService(uuid);
}

// 獲取特征
private BluetoothGattCharacteristic getCharcteristic(String serviceUUID, String characteristicUUID) {
    BluetoothGattService service = getService(UUID.fromString(serviceUUID));
    if (service == null) return null;
    return service.getCharacteristic(UUID.fromString(characteristicUUID));
}

// 讀取數據
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) return;
    mBluetoothGatt.readCharacteristic(characteristic);
}

// 設置通知
public boolean setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) return false;
    return mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
}

七、寫入數據

取得可寫入的 characteristic 後,透過 setValue() 賦值,再呼叫 writeCharacteristic() 發送:

public void write(byte[] data) {
    BluetoothGattCharacteristic writeCharacteristic =
            getCharcteristic(Values.UUID_KEY_SERVICE, Values.UUID_KEY_WRITE);
    if (writeCharacteristic == null) return;
    writeCharacteristic.setValue(data); // 為 characteristic 賦值
    writeCharacteristicWrite(writeCharacteristic);
}

public void writeCharacteristicWrite(BluetoothGattCharacteristic characteristic) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) return;
    boolean isBoolean = mBluetoothGatt.writeCharacteristic(characteristic);
    // isBoolean 返回 true 表示寫入成功
}

八、在 Activity 中調用

在需要搜索藍牙的 Activity 中直接呼叫 startLeScan() 即可,找到目標設備後會自動連接,並透過回調通知結果。搜索成功後,可在按鈕事件中呼叫 write(byte[]) 發送數據,寫入是否成功取決於 writeCharacteristicWrite() 的返回值。

以上便是 Android 與藍牙 BLE 通信的完整流程,從搜索、連接、服務發現到讀寫數據,構成了一套完整的低功耗藍牙交互機制。

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