本文實(shí)例為大家分享了小程序獲取周圍IBeacon設(shè)備的具體代碼,供大家參考,具體內(nèi)容如下
該功能實(shí)現(xiàn)需要使用以下API:
wx.startBeaconDiscovery(OBJECT):開始搜索附近的iBeacon設(shè)備
wx.stopBeaconDiscovery(OBJECT):停止搜索附近的iBeacon設(shè)備
wx.onBeaconUpdate(CALLBACK):監(jiān)聽 iBeacon 設(shè)備的更新事件
wx.openBluetoothAdapter(OBJECT):監(jiān)聽藍(lán)牙狀態(tài)
wx.onBluetoothDeviceFound(CALLBACK):監(jiān)聽藍(lán)牙狀態(tài)切換
具體參數(shù)以及回調(diào)函數(shù)請(qǐng)參考官方API
實(shí)現(xiàn)邏輯:
實(shí)現(xiàn)代碼 index.js:
onShow : function(){ var that = this; //監(jiān)測(cè)藍(lán)牙狀態(tài)的改變 wx.onBluetoothAdapterStateChange(function (res) { if (res.available) {//如果用戶打開藍(lán)牙,開始搜索IBeacon searchBeacon(); } }) //搜索beacons searchBeacon(); //搜索函數(shù) function searchBeacon() { //檢測(cè)藍(lán)牙狀態(tài) wx.openBluetoothAdapter({ success: function (res) {//藍(lán)牙狀態(tài):打開 wx.startBeaconDiscovery({//開始搜索附近的iBeacon設(shè)備 uuids: ['FDA50693-A4E2-4FB1-AFCF-C6EB07647825'],//參數(shù)uuid success: function (res) { wx.onBeaconUpdate(function (res) {//監(jiān)聽 iBeacon 設(shè)備的更新事件 //封裝請(qǐng)求數(shù)據(jù) 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; //請(qǐng)求后臺(tái)向redis插入數(shù)據(jù) redisSave(reqContent); }); }, fail: function (res) { //先關(guān)閉搜索再重新開啟搜索,這一步操作是防止重復(fù)wx.startBeaconDiscovery導(dǎo)致失敗 stopSearchBeacom(); } }) }, fail: function (res) {//藍(lán)牙狀態(tài):關(guān)閉 wx.showToast({ title: "請(qǐng)打開藍(lán)牙", 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" }) } }); } //關(guān)閉成功后開啟搜索 function stopSearchBeacom() { wx.stopBeaconDiscovery({ success: function () { searchBeacon(); } }) } },
介紹小程序的頁(yè)面生命周期函數(shù)之一:onShow
監(jiān)聽頁(yè)面顯示:即每次打開頁(yè)面都會(huì)調(diào)用一次。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選