知識中心

Android 藍牙開發:藍牙 BLE 裝置配對與資料透傳實現全解析

本文詳細介紹 Android 藍牙 BLE 裝置配對與資料透傳的實現方法,包括開發基礎、裝置掃描配對、資料讀寫及常見問題解決,助開發者輕鬆掌握藍牙 BLE 通訊技術。

知識中心 2026-04-16 穩格科技
文章正文知識中心

在萬物互聯的時代,藍牙技術憑藉其低功耗、短距離通訊等優勢,廣泛應用於各類智慧裝置中,尤其是藍牙低功耗(BLE)技術,更是成為智慧穿戴、智慧家居、醫療健康等領域的主流通訊方式。對於 Android 開發者而言,掌握藍牙 BLE 裝置配對與資料透傳的實現方法,是開發相關應用的關鍵技能。本文將深入探討這一主題,為開發者提供全面的指導。


藍牙 BLE 技術概述

藍牙低功耗(BLE)是藍牙 4.0 版本引入的一項重要技術,與傳統藍牙(Classic Bluetooth)相比,BLE 具有顯著的低功耗特性,能夠在支援通訊質量的前提下,大幅降低裝置的能耗,延長電池使用壽命。這使得 BLE 非常適合應用於對功耗要求嚴格的裝置,如智慧手環、心率監測儀等。同時,BLE 還具備快速連線、短資料包傳輸等特點,能夠滿足即時性要求較高的應用場景。

Android 藍牙 BLE 開發基礎

許可權申請

在 Android 應用中開發藍牙 BLE 功能,首先需要在 AndroidManifest.xml 檔案中申請必要的許可權。主要涉及兩個許可權:

xml<uses-permission android:name="android.permission.BLUETOOTH"/><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/><!-- 對於 Android 6.0 及以上系統,還需要動態申請位置許可權,因為藍牙掃描需要獲取裝置位置資訊 --><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

藍牙介面卡初始化

透過 BluetoothManager 獲取 BluetoothAdapter 物件,這是進行藍牙操作的基礎。示例程式碼如下:

javaBluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();if (bluetoothAdapter == null ||!bluetoothAdapter.isEnabled()) {    // 提示使用者開啟藍牙    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);}

藍牙 BLE 裝置配對實現

裝置掃描

使用 BluetoothAdapter 的 startLeScan() 或 BluetoothLeScanner 的 startScan() 方法進行 BLE 裝置掃描。推薦使用 BluetoothLeScanner,因為它提供了更多的掃描過濾選項和更好的效能。示例程式碼如下:

javaBluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();ScanSettings scanSettings = new ScanSettings.Builder()       .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)       .build();List<ScanFilter> scanFilters = new ArrayList<>();// 可以新增掃描過濾條件,如裝置名稱、服務 UUID 等// scanFilters.add(new ScanFilter.Builder().setDeviceName("裝置名稱").build());bluetoothLeScanner.startScan(scanFilters, scanSettings, scanCallback);

其中,scanCallback 是 ScanCallback 物件,用於處理掃描結果:

javaprivate ScanCallback scanCallback = new ScanCallback() {    @Override    public void onScanResult(int callbackType, ScanResult result) {        super.onScanResult(callbackType, result);        BluetoothDevice device = result.getDevice();        // 處理掃描到的裝置    }    @Override    public void onBatchScanResults(List<ScanResult> results) {        super.onBatchScanResults(results);        // 處理批次掃描結果    }    @Override    public void onScanFailed(int errorCode) {        super.onScanFailed(errorCode);        // 處理掃描失敗情況    }};

裝置配對

當掃描到目標裝置後,可以透過 createBond() 方法發起配對請求:

javaBluetoothDevice device =...; // 獲取到的目標裝置if (device.getBondState() == BluetoothDevice.BOND_NONE) {    try {        Method createBondMethod = BluetoothDevice.class.getMethod("createBond");        createBondMethod.invoke(device);    } catch (Exception e) {        e.printStackTrace();    }}

配對過程中,系統會彈出配對確認對話方塊,使用者確認後即可完成配對。配對成功後,裝置的 BondState 會變為 BluetoothDevice.BOND_BONDED。

資料透傳實現

連線裝置

配對成功後,需要建立與裝置的連線。使用 BluetoothGatt 類來實現連線和資料通訊:

javaBluetoothDevice device =...; // 已配對的裝置BluetoothGatt bluetoothGatt = device.connectGatt(this, false, gattCallback);

其中,gattCallback 是 BluetoothGattCallback 物件,用於處理連線狀態變化、服務發現、資料讀寫等事件:

javaprivate BluetoothGattCallback gattCallback = new BluetoothGattCallback() {    @Override    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {        super.onConnectionStateChange(gatt, status, newState);        if (newState == BluetoothProfile.STATE_CONNECTED) {            // 連線成功,開始發現服務            gatt.discoverServices();        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {            // 連線斷開        }    }    @Override    public void onServicesDiscovered(BluetoothGatt gatt, int status) {        super.onServicesDiscovered(gatt, status);        if (status == BluetoothGatt.GATT_SUCCESS) {            // 服務發現成功,獲取服務和特徵            List<BluetoothGattService> services = gatt.getServices();            for (BluetoothGattService service : services) {                List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();                for (BluetoothGattCharacteristic characteristic : characteristics) {                    // 處理特徵                }            }        }    }    @Override    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {        super.onCharacteristicRead(gatt, characteristic, status);        if (status == BluetoothGatt.GATT_SUCCESS) {            // 讀取特徵值成功            byte[] value = characteristic.getValue();            // 處理讀取到的資料        }    }    @Override    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {        super.onCharacteristicWrite(gatt, characteristic, status);        if (status == BluetoothGatt.GATT_SUCCESS) {            // 寫入特徵值成功        }    }    @Override    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {        super.onCharacteristicChanged(gatt, characteristic);        // 特徵值發生變化,處理通知資料        byte[] value = characteristic.getValue();        // 處理接收到的資料    }};

資料讀寫

  • 讀取資料:找到需要讀取的特徵後,呼叫 readCharacteristic() 方法讀取資料:

javaBluetoothGattCharacteristic characteristic =...; // 獲取到的需要讀取的特徵boolean result = bluetoothGatt.readCharacteristic(characteristic);
  • 寫入資料:將資料寫入特徵時,需要先設定特徵的寫入許可權,然後呼叫 writeCharacteristic() 方法:

javaBluetoothGattCharacteristic characteristic =...; // 獲取到的需要寫入的特徵characteristic.setValue(data); // data 為要寫入的資料characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);boolean result = bluetoothGatt.writeCharacteristic(characteristic);

開啟通知

如果需要接收裝置傳送的即時資料,可以開啟特徵的通知功能:

javaBluetoothGattCharacteristic characteristic =...; // 獲取到的需要開啟通知的特徵BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));characteristic.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);boolean result = bluetoothGatt.writeDescriptor(descriptor);

常見問題與解決方案

連線失敗

連線失敗可能是由於裝置未開啟、距離過遠、裝置忙等原因導致。解決方法包括檢查裝置狀態、縮短連線距離、等待裝置空閒後重試等。

資料讀寫失敗

資料讀寫失敗可能是由於特徵許可權不足、裝置未就緒等原因引起。需要有助於支援特徵具有相應的讀寫許可權,並在裝置就緒後進行讀寫操作。


提交專案需求

留下聯絡方式和需求簡述,便於我們判斷技術方向、交付範圍和溝通方式。

線上諮詢
電話諮詢
13910119357
微信諮詢
WhatsApp
穩格科技 WhatsApp 二維碼 掃碼或點選聯絡
回到頂部