鸿蒙Next蓝牙协议如何使用?

在鸿蒙Next系统中,如何正确配置和使用蓝牙协议进行设备连接?具体需要哪些API接口或权限?开发过程中需要注意哪些常见问题?是否有完整的示例代码可以参考?

2 回复

鸿蒙Next的蓝牙协议?简单说就是:先别急着配对,先看看文档!不然设备可能以为你在玩“躲猫猫”,直接给你表演“蓝牙已断开”的魔术。记住:调用API前,记得先申请权限,不然手机会用沉默抗议你的“无礼行为”。

更多关于鸿蒙Next蓝牙协议如何使用?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


鸿蒙Next(HarmonyOS NEXT)中蓝牙开发主要基于@ohos.bluetooth接口,以下是核心使用步骤及示例代码:


1. 权限配置

module.json5中添加权限:

{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.USE_BLUETOOTH",
        "reason": "控制蓝牙设备"
      },
      {
        "name": "ohos.permission.LOCATION",
        "reason": "扫描蓝牙设备需定位权限"
      }
    ]
  }
}

2. 基础功能实现

启用/禁用蓝牙

import { bluetoothManager } from '@ohos.bluetooth';

// 启用蓝牙
async function enableBluetooth() {
  try {
    await bluetoothManager.enableBluetooth();
    console.log('蓝牙已开启');
  } catch (err) {
    console.error('开启失败:', err.code);
  }
}

// 禁用蓝牙
async function disableBluetooth() {
  try {
    await bluetoothManager.disableBluetooth();
  } catch (err) {
    console.error('禁用失败:', err.code);
  }
}

扫描设备

import { bluetoothManager } from '@ohos.bluetooth';

// 开始扫描
bluetoothManager.startBluetoothDiscovery();

// 监听设备发现
bluetoothManager.on('bluetoothDeviceFind', (devices) => {
  devices.forEach(device => {
    console.log(`发现设备: ${device.deviceName}, MAC: ${device.deviceId}`);
  });
});

// 停止扫描
bluetoothManager.stopBluetoothDiscovery();

3. 设备连接与通信

BLE连接(客户端)

import { gattClient } from '@ohos.bluetooth';

// 连接设备
const deviceId = 'XX:XX:XX:XX:XX:XX'; // 目标设备MAC
const client = gattClient.createGattClientDevice(deviceId);

// 连接并发现服务
client.connect().then(() => {
  console.log('连接成功');
  return client.discoverServices();
}).then(services => {
  services.forEach(service => {
    console.log(`服务UUID: ${service.serviceUuid}`);
  });
});

数据传输

// 写入特征值(需先获取characteristic对象)
characteristic.writeValue(new Uint8Array([0x01, 0x02]))
  .then(() => console.log('写入成功'))
  .catch(err => console.error('写入失败:', err));

// 订阅通知
characteristic.on('characteristicValueChange', (value) => {
  console.log('收到数据:', Array.from(value));
});
characteristic.setNotifyValue(true);

4. 服务端开发(仅系统应用支持)

import { gattServer } from '@ohos.bluetooth';

// 创建GATT服务
const service = gattServer.createService({
  serviceUuid: '0000180F-0000-1000-8000-00805F9B34FB'
});

// 添加特征值
service.addCharacteristic({
  characteristicUuid: '00002A19-0000-1000-8000-00805F9B34FB',
  permissions: { read: true, write: true },
  properties: { read: true, write: true }
});

// 启动服务
gattServer.startAdvertising({
  serviceUuids: ['0000180F-0000-1000-8000-00805F9B34FB']
});

关键注意事项

  1. 兼容性:部分接口仅对系统应用开放,普通应用需使用受限功能
  2. 权限管理:需动态申请定位权限(API 9+)
  3. 设备过滤:扫描时可通过filters指定服务UUID缩小范围
  4. 资源释放:断开连接时调用disconnect()close()

建议参考官方蓝牙开发指南获取最新API说明。

回到顶部