uni-app onBluetoothDeviceFound不执行回调

uni-app onBluetoothDeviceFound不执行回调

开发环境 版本号 项目创建方式
Mac 12.6.4
HBuilderX 3.95

示例代码:

uni.onBluetoothDeviceFound(devices => {  
    uni.getBluetoothDevices({  
        success(res) {  
            console.log("获取到的设备")

操作步骤:

预期结果:

希望执行回调

实际结果:

不执行

bug描述:

uni.openBluetoothAdapter正常打开 { “errMsg”: “openBluetoothAdapter:ok” }

uni.startBluetoothDevicesDiscovery正常执行 { “errMsg”: “startBluetoothDevicesDiscovery:ok” } 但是onBluetoothDeviceFound 不执行回调 uni.onBluetoothDeviceFound(devices => { console.log("设备


更多关于uni-app onBluetoothDeviceFound不执行回调的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

已解决 去掉startBluetoothDevicesDiscovery 的services参数就可以嘞 之前的参数是services:[“0000FFE0-0000-1000-8000-00805F9B34FB”] 现在换成services:[“FFE0”]就没问题了,奇怪的是只有安卓有问题

更多关于uni-app onBluetoothDeviceFound不执行回调的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在 Uni-App 中,onBluetoothDeviceFound 是一个用于监听蓝牙设备发现的回调函数。如果你发现这个回调不执行,可能是由于以下几个原因:

1. 蓝牙适配器未初始化

在调用 onBluetoothDeviceFound 之前,必须先初始化蓝牙适配器。确保你已经调用了 uni.openBluetoothAdapter 并且成功初始化。

uni.openBluetoothAdapter({
  success(res) {
    console.log('蓝牙适配器初始化成功');
    // 开始搜索蓝牙设备
    uni.startBluetoothDevicesDiscovery({
      success(res) {
        console.log('开始搜索蓝牙设备');
      },
      fail(err) {
        console.error('开启搜索失败', err);
      }
    });
  },
  fail(err) {
    console.error('蓝牙适配器初始化失败', err);
  }
});

2. 未调用 startBluetoothDevicesDiscovery

onBluetoothDeviceFound 只有在调用 uni.startBluetoothDevicesDiscovery 后才会触发。确保你已经成功调用了这个方法。

uni.startBluetoothDevicesDiscovery({
  success(res) {
    console.log('开始搜索蓝牙设备');
  },
  fail(err) {
    console.error('开启搜索失败', err);
  }
});

3. 回调函数未正确注册

确保你已经正确注册了 onBluetoothDeviceFound 回调函数。

uni.onBluetoothDeviceFound(function(res) {
  console.log('发现蓝牙设备', res.devices);
});

4. 设备未开启蓝牙

确保设备的蓝牙功能已经开启,否则无法搜索到蓝牙设备。

5. 权限问题

在某些平台上(如 Android),可能需要申请蓝牙权限。确保你的应用已经获取了必要的权限。

{
  "permission": {
    "scope.bluetooth": {
      "desc": "需要蓝牙权限以搜索设备"
    }
  }
}

6. 平台兼容性问题

Uni-App 的蓝牙 API 在不同平台上可能存在兼容性问题。确保你使用的 API 在目标平台上支持。

7. 调试信息

在调试时,可以通过 uni.getBluetoothAdapterState 来获取当前蓝牙适配器的状态,确认蓝牙是否正常开启。

uni.getBluetoothAdapterState({
  success(res) {
    console.log('蓝牙适配器状态', res);
  },
  fail(err) {
    console.error('获取蓝牙适配器状态失败', err);
  }
});
回到顶部