蓝牙 API 平台差异说明

uni.openBluetoothAdapter(OBJECT)

初始化蓝牙模块 OBJECT 参数说明

错误

注意

  • 调用之后使用。否则 API 会返回错误(errCode=10000)。
  • 会返回错误(errCode=10001),表示手机蓝牙功能不可用。此时APP蓝牙模块已经初始化完成,可通过 监听手机蓝牙状态的改变,也可以调用蓝牙模块的所有API。示例代码
    1. uni.openBluetoothAdapter({ success(res) { console.log(res) }})

    uni.startBluetoothDevicesDiscovery(OBJECT)

    此操作比较耗费系统资源,请在搜索并连接到设备后调用 OBJECT 参数说明

    错误

    注意:
  • https://ask.dcloud.net.cn/article/114。**示例代码**
    1. // 以微信硬件平台的蓝牙智能灯为例,主服务的 UUID 是 FEE7。传入这个参数,只搜索主服务 UUID 为 FEE7 的设备uni.startBluetoothDevicesDiscovery({ services: ['FEE7'], success(res) { console.log(res) }})

    uni.onBluetoothDeviceFound(CALLBACK)

    监听寻找到新设备的事件 CALLBACK 返回参数 devices 的结构 注意
  • 回调了某个设备,则此设备会添加到 接口获取到的数组中。示例代码
    1. // ArrayBuffer转16进度字符串示例function ab2hex(buffer) { const hexArr = Array.prototype.map.call( new Uint8Array(buffer), function (bit) { return ('00' + bit.toString(16)).slice(-2) } ) return hexArr.join('')}uni.onBluetoothDeviceFound(function (devices) { console.log('new device list has founded') console.dir(devices) console.log(ab2hex(devices[0].advertisData))})

    uni.stopBluetoothDevicesDiscovery(OBJECT)

    停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。 OBJECT 参数说明

    错误

    示例代码
    1. uni.stopBluetoothDevicesDiscovery({ success(res) { console.log(res) }})

    uni.onBluetoothAdapterStateChange(CALLBACK)

    监听蓝牙适配器状态变化事件 CALLBACK 返回参数 示例代码
    1. uni.onBluetoothAdapterStateChange(function (res) { console.log('adapterState changed, now is', res)})

    uni.getConnectedBluetoothDevices(OBJECT)

    根据 uuid 获取处于已连接状态的设备。 OBJECT 参数说明 success 返回参数说明: res.devices 的结构

    错误

    示例代码
    1. uni.getConnectedBluetoothDevices({ success(res) { console.log(res) }})

    uni.getBluetoothDevices(OBJECT)

    获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。 OBJECT 参数说明 success 返回参数说明: res.devices 的结构

    错误

    示例代码
    1. // ArrayBuffer转16进度字符串示例function ab2hex(buffer) { const hexArr = Array.prototype.map.call( new Uint8Array(buffer), function (bit) { return ('00' + bit.toString(16)).slice(-2) } ) return hexArr.join('')}uni.getBluetoothDevices({ success(res) { console.log(res) if (res.devices[0]) { console.log(ab2hex(res.devices[0].advertisData)) } }})
    注意
  • 蓝牙模块生效期间所有搜索到的蓝牙设备,若在蓝牙模块使用流程结束后未及时调用 释放资源,会存在调用该接口会返回之前的蓝牙使用流程中搜索到的蓝牙设备,可能设备已经不在用户身边,无法连接。
  • GattName。若需要动态改变设备名称并展示,建议使用 localName 字段。

    uni.getBluetoothAdapterState(OBJECT)

    获取本机蓝牙适配器状态。 OBJECT 参数说明 success 返回参数说明:

    错误

    示例代码
    1. uni.getBluetoothAdapterState({ success(res) { console.log(res) }})

    uni.closeBluetoothAdapter(OBJECT)

    成对调用。 OBJECT 参数说明

    错误

    示例代码
    1. uni.closeBluetoothAdapter({ success(res) { console.log(res) }})

在 GitHub 上编辑此页面!