蓝牙功能当手机的蓝牙是关闭再开启的时候,数据一直不停的更新?
发布于 5 年前 作者 twang 405 次浏览 来自 官方Issues
// pages/unlock/bluetoothlock/bluetoothlock.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showNav: true,
    bluetoothStatus: false
  },
  // 初始化蓝牙设备
  openBluetoothAdapter() {
    //监听是否打开了蓝牙设备
    let that = this
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('蓝牙设备成功', res)
        if (res.errMsg == "openBluetoothAdapter:ok") {
          // 监听蓝牙设备状态 
          that.startBluetoothDevicesDiscovery()
        }
      },
      fail: (res) => {
        console.log('蓝牙设备失败', res)
        if (res.errCode === 10001) {
          // 监听蓝牙是否开启了状态
          that.onBluetoothAdapterStateChange()  // 在这里一直重复的调用数据
        }
      }
    })
  },
  //监听蓝牙是否开启了状态
  onBluetoothAdapterStateChange() {
    let that = this
    wx.onBluetoothAdapterStateChange(function(res) {
      console.log('是否开启了蓝牙', res)
      //判断蓝牙适配器是否处于搜索状态
      // 判断设配蓝牙适配器是否可用
      if (res.available) {
        that.setData({
          bluetoothStatus: true
        })
        that.startBluetoothDevicesDiscovery()    
      }

    })
  },
  // 搜寻附近的蓝牙外围设备
  startBluetoothDevicesDiscovery() {
    let that = this
    wx.startBluetoothDevicesDiscovery({
      services: [],
      allowDuplicatesKey: false,
      success(res) {
        console.log('是否处于搜索状态', res)
        if (res.errCode == 0) {
          that.stopBluetoothDevicesDiscovery()
        }
      },
      fail(res) {
        console.log(res)
        // that.stopBluetoothDevicesDiscovery()
      }
    })
  },
  // 停止外围设备搜索,当搜索完毕要停止
  stopBluetoothDevicesDiscovery() {
    let that = this
    wx.stopBluetoothDevicesDiscovery({
      success(res) {
        console.log('停止设备', res)
        if (res.errMsg == 'stopBluetoothDevicesDiscovery:ok') {
          that.getBluetoothDevices()
        }
      }
    })
  },

  // 获取蓝牙设备列表
  getBluetoothDevices() {
    function ab2hex(buffer) {
      var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function(bit) {
          return ('00' + bit.toString(16)).slice(-2)
        }
      )
      return hexArr.join('');
    }
    wx.getBluetoothDevices({
      success: function(res) {
        console.log(res)
        if (res.errMsg == 'getBluetoothDevices:ok') {

        }
        if (res.devices[0]) {
          console.log(ab2hex(res.devices[0].advertisData))
        }
      }
    })
  },
  //断开所有已建立的连接并释放系统资源建议在使用蓝牙流程后,wx.openBluetoothAdapter 成对调用
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter({
      success(res) {
        console.log(res)
      }
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.openBluetoothAdapter()
  },

})
1 回复

麻烦在手机微信那里上传下日志: 我->设置->帮助与反馈右上角有个上报日志的入口,麻烦提供一下微信号,时间点

回到顶部