当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 小程序获取周围IBeacon设备的方法

小程序获取周围IBeacon设备的方法

2018年11月05日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了小程序获取周围ibeacon设备的具体代码,供大家参考,具体内容如下

该功能实现需要使用以下api:

wx.startbeacondiscovery(object):开始搜索附近的ibeacon设备

wx.stopbeacondiscovery(object):停止搜索附近的ibeacon设备

wx.onbeaconupdate(callback):监听 ibeacon 设备的更新事件

wx.openbluetoothadapter(object):监听蓝牙状态

wx.onbluetoothdevicefound(callback):监听蓝牙状态切换

具体参数以及回调函数请参考官方api

实现逻辑:

实现代码 index.js:

onshow : function(){
 var that = this;
 //监测蓝牙状态的改变
 wx.onbluetoothadapterstatechange(function (res) {
  if (res.available) {//如果用户打开蓝牙,开始搜索ibeacon
  searchbeacon();
  }
 })
 
 //搜索beacons
 searchbeacon();
 //搜索函数
 function searchbeacon() {
  //检测蓝牙状态
  wx.openbluetoothadapter({
  success: function (res) {//蓝牙状态:打开
   wx.startbeacondiscovery({//开始搜索附近的ibeacon设备
   uuids: ['fda50693-a4e2-4fb1-afcf-c6eb07647825'],//参数uuid
   success: function (res) {
    wx.onbeaconupdate(function (res) {//监听 ibeacon 设备的更新事件 
    //封装请求数据 
    var beacons = res.beacons;
    var reqcontent = {};
    var blearray = [];
    for (var i = 0; i < beacons.length; i++) {
     var bleobj = {};
     bleobj.distance = beacons[i].accuracy;
     bleobj.rssi = beacons[i].rssi;
     bleobj.mac = beacons[i].major + ":" + beacons[i].minor;
     blearray.push(bleobj);
    }
    reqcontent.ble = blearray;
    //请求后台向redis插入数据
    redissave(reqcontent);
    });
   },
   fail: function (res) {
    //先关闭搜索再重新开启搜索,这一步操作是防止重复wx.startbeacondiscovery导致失败
    stopsearchbeacom();
   }
   })
  },
  fail: function (res) {//蓝牙状态:关闭
   wx.showtoast({ title: "请打开蓝牙", icon: "none", duration: 2000 })
  }
  })
 }
 function redissave(reqcontent) {
  wx.request({
  url: "https://map.intmote.com/locateserver/location.action",
  data: json.stringify(reqcontent),
  method: 'post',
  header: {
   'content-type': 'application/json'
  },
  success: function (res) {
   // wx.showtoast({ title: "seccess" })
  },
  fail: function (res) {
   // wx.showtoast({ title: "1" })
  }
  });
 }
 //关闭成功后开启搜索
 function stopsearchbeacom() {
  wx.stopbeacondiscovery({
  success: function () {
   searchbeacon();
  }
  })
 } 
 },

介绍小程序的页面生命周期函数之一:onshow

监听页面显示:即每次打开页面都会调用一次。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网