小程序学习日记-微信5-蓝牙方式发现共享单车蓝牙设备

实现思路:

  1. 开启蓝牙适配器
  2. 启用蓝牙发现服务
  3. 增加监听器,监听蓝牙设备。
  4. 发现一个共享单车后,获取蓝牙数据并展示到控制台。
  5. 关闭蓝牙发现服务
  6. 关闭蓝牙适配器

为了实现这个功能

  • 准备实现方法:文件 blueTooth.js - openBluetooth
openBluetooth: function () {
    console.log("开始启动蓝牙");
    wx.openBluetoothAdapter({
      complete(){
        console.log("蓝牙启动完成");
      },
      success(res) {
        console.log("蓝牙启动成功");
        console.log(res);
        var blueToothCount=0;
        wx.startBluetoothDevicesDiscovery({
          allowDuplicatesKey: false,
          success(res) {
            console.log("启动蓝牙发现服务");
            console.log(res);
            wx.onBluetoothDeviceFound(function (res) {
              var devices = res.devices;
              blueToothCount+=devices.length;
              console.log('new device list has founded,total Count:'+blueToothCount);
              console.log(devices);
              devices.forEach(element => {
                if(element.name.startsWith("mobike")){
                  console.log("摩拜单车蓝牙设备已找到");
                  console.log(element);
                  // 找到摩拜单车就关闭
                  wx.stopBluetoothDevicesDiscovery({
                    success (res) {
                      console.log("关闭蓝牙发现器");
                      console.log(res)
                    }
                  });
                }
              });
             
            });
          },
          fail(res) {
            console.log("启动发现服务失败");
            console.log(res);
          }
        });
      },
      fail(res) {
        console.log("蓝牙启动失败");
        console.log(res);
      }
    });
  }
  • 创建一个页面按钮触发事件:绑定方法-openBluetooth
<button bindtap="openBluetooth">启动蓝牙适配器</button>
  • 点击真机调试进行测试

  • 点击按钮进行测试,下图为日志输出效果。

  •  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值