本文實例為大家分享了小程序獲取周圍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
監聽頁面顯示:即每次打開頁面都會調用一次。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答