鸿蒙系统下蓝牙连接开发详解

2025-06发布4次浏览

蓝牙连接开发是鸿蒙系统中一个非常重要的功能模块,它允许设备之间进行无线通信和数据交换。在鸿蒙系统下开发蓝牙功能需要理解其架构、API使用方法以及实现步骤。本文将详细介绍如何在鸿蒙系统中实现蓝牙设备的扫描、连接和数据传输。


一、鸿蒙系统蓝牙开发基础

鸿蒙系统的蓝牙开发基于HarmonyOS提供的Bluetooth API,支持经典蓝牙(Bluetooth Classic)和低功耗蓝牙(Bluetooth Low Energy, BLE)。开发者可以通过这些API实现设备扫描、连接管理、数据传输等功能。

1. 鸿蒙蓝牙开发环境准备

在开始蓝牙开发之前,需要确保以下条件:

  • 已安装鸿蒙开发环境(DevEco Studio)。
  • 设备支持蓝牙功能,并已启用蓝牙。
  • 添加必要的权限声明到config.json文件中。

权限声明

config.json中添加蓝牙相关权限:

"reqPermissions": [
    {
        "name": "ohos.permission.BLUETOOTH_ADMIN"
    },
    {
        "name": "ohos.permission.BLUETOOTH"
    }
]

二、蓝牙设备扫描

蓝牙设备扫描是蓝牙开发的第一步,用于发现周围可用的蓝牙设备。

1. 开始扫描

通过调用BluetoothAdapter.startDiscovery()方法启动设备扫描。以下是具体步骤:

示例代码

import ohos.bluetooth.BluetoothAdapter;
import ohos.bluetooth.BluetoothDevice;

public class BluetoothScanExample {
    private BluetoothAdapter bluetoothAdapter;

    public void startScan() {
        if (bluetoothAdapter == null) {
            bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        }

        if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.startDiscovery();
            System.out.println("蓝牙扫描已启动");
        } else {
            System.out.println("蓝牙未启用或不可用");
        }
    }

    public void onDeviceFound(BluetoothDevice device) {
        System.out.println("发现设备: " + device.getName() + ", 地址: " + device.getAddress());
    }
}

2. 停止扫描

为了避免过度消耗资源,扫描完成后应调用stopDiscovery()方法停止扫描。


三、蓝牙设备连接

蓝牙设备连接分为经典蓝牙和BLE两种模式。以下是两种模式的连接实现方式。

1. 经典蓝牙连接

经典蓝牙连接通常用于音频、文件传输等场景。连接过程包括建立RFCOMM通道和Socket通信。

步骤说明

  1. 获取目标设备的MAC地址。
  2. 使用createRfcommSocketToServiceRecord(UUID)创建Socket。
  3. 调用connect()方法建立连接。

示例代码

import java.util.UUID;

public void connectClassicBluetooth(BluetoothDevice device) {
    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // 标准UUID
    try {
        BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
        socket.connect();
        System.out.println("经典蓝牙连接成功");
    } catch (Exception e) {
        System.out.println("经典蓝牙连接失败: " + e.getMessage());
    }
}

2. BLE连接

BLE连接主要用于低功耗场景,如可穿戴设备、智能家居等。连接过程包括GATT服务的绑定和特征值读写。

GATT服务绑定流程

sequenceDiagram
    participant App as 应用程序
    participant BLEDevice as BLE设备
    participant GATTServer as GATT服务器

    App->>BLEDevice: 发起连接请求
    BLEDevice-->>App: 返回连接状态
    App->>GATTServer: 发现服务
    GATTServer-->>App: 返回服务列表
    App->>GATTServer: 读取/写入特征值
    GATTServer-->>App: 返回结果

示例代码

import ohos.bluetooth.BluetoothGatt;
import ohos.bluetooth.BluetoothGattCallback;
import ohos.bluetooth.BluetoothGattCharacteristic;

public class BLEConnectionExample {
    private BluetoothGatt bluetoothGatt;

    public void connectBLE(BluetoothDevice device) {
        bluetoothGatt = device.connectGatt(this, false, new BluetoothGattCallback() {
            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                if (newState == BluetoothGatt.STATE_CONNECTED) {
                    System.out.println("BLE连接成功");
                } else {
                    System.out.println("BLE连接失败");
                }
            }

            @Override
            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    System.out.println("服务发现成功");
                }
            }

            @Override
            public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    System.out.println("特征值读取成功: " + characteristic.getStringValue(0));
                }
            }
        });
    }
}

四、蓝牙数据传输

蓝牙数据传输可以通过Socket或GATT协议实现。以下是两种方式的数据传输示例。

1. Socket数据传输

使用经典蓝牙的Socket进行数据传输。

示例代码

public void sendDataViaSocket(BluetoothSocket socket, String data) {
    try {
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(data.getBytes());
        System.out.println("数据发送成功: " + data);
    } catch (Exception e) {
        System.out.println("数据发送失败: " + e.getMessage());
    }
}

2. GATT数据传输

使用BLE的GATT协议进行特征值读写。

示例代码

public void writeCharacteristic(BluetoothGattCharacteristic characteristic, byte[] value) {
    characteristic.setValue(value);
    boolean success = bluetoothGatt.writeCharacteristic(characteristic);
    if (success) {
        System.out.println("特征值写入成功");
    } else {
        System.out.println("特征值写入失败");
    }
}

五、常见问题与解决方案

  1. 蓝牙扫描无法发现设备
    确保目标设备处于可被发现的状态,并检查是否有权限问题。

  2. BLE连接断开频繁
    检查GATT回调中的onConnectionStateChange是否返回异常状态,优化重连逻辑。

  3. 数据传输延迟高
    使用BLE时尽量选择小包数据传输,并调整MTU大小以提高效率。