鸿蒙Next API 9 蓝牙开发问题求助
在鸿蒙Next API 9上进行蓝牙开发时遇到以下问题:
- 调用
bluetooth.startDiscovery()方法后,设备列表无法正常刷新,偶尔会返回空列表 - 使用
bluetooth.createBond()配对设备时经常失败,错误码显示-1(未明确错误类型) - 低功耗蓝牙(BLE)连接后,
characteristic.value读取到的数据总是为null - 调用
bluetooth.stopDiscovery()后蓝牙扫描似乎没有真正停止
开发环境:
- DevEco Studio 4.0 Beta2
- 真机测试设备:华为P50(HarmonyOS 4.0)
- API版本:9
已尝试过重启设备、重装应用、检查权限设置,问题依旧存在。是否有遇到类似情况的开发者?求解决方案或排查思路。
更多关于鸿蒙Next API 9 蓝牙开发问题求助的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
哈哈,遇到蓝牙开发难题了?别慌,API 9的蓝牙就像个傲娇的猫——你得先检查权限(ohos.permission.USE_BLUETOOTH),再用profileManager.connect()温柔连接。如果设备不响应,试试重启蓝牙或者检查设备是否在“撩骚模式”(可见状态)。记住:代码可以冷,但调试的心要热!
更多关于鸿蒙Next API 9 蓝牙开发问题求助的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在鸿蒙Next(API 9)中进行蓝牙开发,主要涉及设备扫描、连接、数据传输等步骤。以下是关键流程和示例代码:
1. 权限配置
在 module.json5 中声明蓝牙权限:
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.DISCOVER_BLUTOOTH",
"reason": "扫描蓝牙设备"
},
{
"name": "ohos.permission.MANAGE_BLUTOOTH",
"reason": "管理蓝牙连接"
},
{
"name": "ohos.permission.ACCESS_BLUTOOTH",
"reason": "访问蓝牙服务"
}
]
}
}
2. 初始化蓝牙适配器
import bluetooth from '@ohos.bluetooth';
// 获取蓝牙适配器
let adapter = bluetooth.getDefaultAdapter();
// 开启蓝牙(需用户授权)
adapter.enableBluetooth().then(() => {
console.log("蓝牙已开启");
});
3. 扫描蓝牙设备
// 注册扫描回调
adapter.on('bluetoothDeviceFind', (devices: Array<bluetooth.BluetoothDevice>) => {
devices.forEach(device => {
console.log(`发现设备: ${device.deviceName}, MAC: ${device.deviceId}`);
});
});
// 开始扫描
adapter.startBluetoothDevicesDiscovery().then(() => {
console.log("开始扫描");
});
// 停止扫描(示例:10秒后停止)
setTimeout(() => {
adapter.stopBluetoothDevicesDiscovery();
console.log("停止扫描");
}, 10000);
4. 连接设备与通信
以 GATT 连接为例:
import { gatt } from '@ohos.bluetooth';
// 建立 GATT 连接
let deviceId = "XX:XX:XX:XX:XX:XX"; // 目标设备 MAC
let client = gatt.createGattClientDevice(deviceId);
// 连接设备
client.connect().then(() => {
console.log("GATT 连接成功");
// 发现服务
return client.discoverServices();
}).then(services => {
// 遍历服务特征值
services.forEach(service => {
service.characteristics.forEach(char => {
console.log(`特征值 UUID: ${char.characteristicUuid}`);
});
});
});
5. 数据传输
// 写入数据(需获取特征值对象)
characteristic.writeValue(new Uint8Array([0x01, 0x02])).then(() => {
console.log("数据写入成功");
});
// 订阅通知
characteristic.on('characteristicValueChange', (value: Uint8Array) => {
console.log("收到数据:", value);
});
characteristic.setNotifyValue(true); // 启用通知
常见问题
- 扫描不到设备:检查权限、设备是否可见、物理距离。
- 连接失败:确认设备支持 GATT 协议,MAC 地址正确。
- 服务发现为空:部分设备需先配对(
adapter.pairDevice(deviceId))。
建议参考 官方蓝牙文档 获取完整 API 说明。

