HarmonyOS鸿蒙Next中使用connection.on('bluetoothDeviceFind'报错,2900099
HarmonyOS鸿蒙Next中使用connection.on('bluetoothDeviceFind’报错,2900099
try {
connection.on('bluetoothDeviceFind', (data: Array<string>) => {
console.info("蓝牙扫描1", '设备名称 = ' + this.isBusying);
if (this.isBusying) {
return;
}
if (data.length > 0) {
let macAddress = data[0];
try {
let remoteDeviceName: string = connection.getRemoteDeviceName(macAddress);
if (!remoteDeviceName) {
return
}
console.info("蓝牙扫描", '设备名称 = ' + remoteDeviceName + ' MAC地址:' + macAddress);
if (remoteDeviceName.length > 10) {
this.isBusying = true;
let record: Record<string, string> = {"name" : remoteDeviceName, "address" : macAddress};
if (this.readerList.length > 0) {
let isHave = false;
for (let readerListElement of this.readerList) {
if (readerListElement.address == record.address) {
isHave = true;
break;
}
}
if (!isHave) {
this.readerList.push(record)
}
} else {
this.readerList.push(record)
}
setTimeout(() => this.isBusying = false, 500);
}
} catch (err) {
}
}
});
connection.startBluetoothDiscovery();
} catch (err) {
//会在这catch到错误,2900099
}
点击搜索蓝牙时,会catch到2900099错误,有时候第一次点击就会触发,如果第一次没出现想要的设备,再次点击会更容易触发,但是也不是一定报错,我在再次点击前使用connection.stopBluetoothDiscovery();也还是一样,这是什么原因,哪位大神帮忙指导下?
更多关于HarmonyOS鸿蒙Next中使用connection.on('bluetoothDeviceFind'报错,2900099的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
在HarmonyOS中,错误码2900099通常表示蓝牙权限未正确配置。需要在config.json中声明ohos.permission.USE_BLUETOOTH
和ohos.permission.LOCATION
权限。检查设备是否开启蓝牙功能,并确保应用已获取必要权限。connection.on('bluetoothDeviceFind')
需在调用connection.startBluetoothDiscovery()
之后使用。错误也可能因未正确初始化蓝牙适配器导致。
更多关于HarmonyOS鸿蒙Next中使用connection.on('bluetoothDeviceFind'报错,2900099的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
错误代码2900099通常表示蓝牙权限或状态问题。在HarmonyOS Next中,使用蓝牙功能需要注意以下几点:
- 确保已添加必要的权限:
在
config.json
中添加:
"reqPermissions": [
{
"name": "ohos.permission.USE_BLUETOOTH"
},
{
"name": "ohos.permission.DISCOVER_BLUETOOTH"
},
{
"name": "ohos.permission.MANAGE_BLUETOOTH"
}
]
- 检查蓝牙适配器状态:
在调用
startBluetoothDiscovery
前,应先确认:
let adapter = connection.getDefaultAdapter();
if (!adapter || !adapter.isEnable()) {
// 需要先启用蓝牙
return;
}
- 避免重复扫描:
确保每次调用
startBluetoothDiscovery
前都先调用stopBluetoothDiscovery
,并添加适当延迟:
connection.stopBluetoothDiscovery();
setTimeout(() => {
connection.startBluetoothDiscovery();
}, 500);
- 错误处理: 2900099可能是蓝牙资源被占用或状态异常,建议增加重试机制:
let retryCount = 0;
const maxRetry = 3;
function startDiscovery() {
try {
connection.startBluetoothDiscovery();
} catch (err) {
if (err.code === 2900099 && retryCount < maxRetry) {
retryCount++;
setTimeout(startDiscovery, 1000);
}
}
}
- 确保设备蓝牙功能正常: 部分设备可能有蓝牙硬件限制,建议在真机上测试。