收藏
回答

红米手机不能获取蓝牙设备

框架类型 问题类型 API/组件名称 终端类型 微信版本 基础库版本
小程序 Bug wx.getBluetoothDevices() 微信安卓客户端 8.0.49 3.4.9

wx.getBluetoothDevices()红米机型获取不到蓝牙设备列表,官方给的示例代码

const app = getApp()


function inArray(arr, key, val{
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}


// ArrayBuffer转16进度字符串示例
function ab2hex(buffer{
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit{
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}


Page({
  data: {
    devices: [],
    connectedfalse,
    chs: [],
  },
  openBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success(res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail(res) => {
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res{
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success(res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKeytrue,
      success(res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  },
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData(data)
      })
    })
  },
  createBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    wx.createBLEConnection({
      deviceId,
      success(res) => {
        this.setData({
          connectedtrue,
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      }
    })
    this.stopBluetoothDevicesDiscovery()
  },
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceIdthis.data.deviceId
    })
    this.setData({
      connectedfalse,
      chs: [],
      canWritefalse,
    })
  },
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success(res) => {
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      }
    })
  },
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success(res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWritetrue
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              statetrue,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听,保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      this.setData(data)
    })
  },
  writeBLECharacteristicValue() {
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setUint8(0Math.random() * 255 | 0)
    wx.writeBLECharacteristicValue({
      deviceIdthis._deviceId,
      serviceIdthis._serviceId,
      characteristicIdthis._characteristicId,
      value: buffer,
    })
  },
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },
})


回答关注问题邀请回答
收藏

1 个回答

  • Demons
    Demons
    07-07

    请具体描述问题出现的流程,并提供能复现问题的简单代码片段(https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html)。

    07-07
    有用
    回复 5
    • 善悪~真実
      善悪~真実
      07-07
      你好,红米K70使用openBluetoothAdapterAPI时会出现错误回调undefined,能不能解决一下
      07-07
      回复
    • HTTP-200
      HTTP-200
      07-08
      也遇到这种问题,红米note10 和小米6、苹果16 搜索蓝牙设备搜索不到。其他型号的手机可以搜索得到。认为不应该是代码的问题,如果是代码的问题,其他型号的手机也应该搜索不到才对。并且手机定位也已经开启了。专门写了2个弹窗用来获取蓝牙和位置信息的权限。结果还是这样,搜不到设备。想请问一下,是手机兼容性的问题吗? 有办法解决吗?
      07-08
      回复
    • Demons
      Demons
      07-10回复善悪~真実
      请具体描述问题出现的流程,并提供能复现问题的简单代码片段(https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html)。
      07-10
      回复
    • Demons
      Demons
      07-10
      请具体描述问题出现的流程,并提供能复现问题的简单代码片段(https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html)。
      07-10
      回复
    • 善悪~真実
      善悪~真実
      07-11回复Demons
      这个不是可以固定复现的,偶尔会出现,主要体现在小米手机上
      07-11
      回复
登录 后发表内容