小程序獲取周圍IBeacon設(shè)備的方法
本文實例為大家分享了小程序獲取周圍IBeacon設(shè)備的具體代碼,供大家參考,具體內(nèi)容如下
該功能實現(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)聽藍牙狀態(tài)
wx.onBluetoothDeviceFound(CALLBACK):監(jiān)聽藍牙狀態(tài)切換
具體參數(shù)以及回調(diào)函數(shù)請參考官方API
實現(xiàn)邏輯:

實現(xiàn)代碼 index.js:
onShow : function(){
var that = this;
//監(jiān)測藍牙狀態(tài)的改變
wx.onBluetoothAdapterStateChange(function (res) {
if (res.available) {//如果用戶打開藍牙,開始搜索IBeacon
searchBeacon();
}
})
//搜索beacons
searchBeacon();
//搜索函數(shù)
function searchBeacon() {
//檢測藍牙狀態(tài)
wx.openBluetoothAdapter({
success: function (res) {//藍牙狀態(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è)備的更新事件
//封裝請求數(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;
//請求后臺向redis插入數(shù)據(jù)
redisSave(reqContent);
});
},
fail: function (res) {
//先關(guān)閉搜索再重新開啟搜索,這一步操作是防止重復(fù)wx.startBeaconDiscovery導(dǎo)致失敗
stopSearchBeacom();
}
})
},
fail: function (res) {//藍牙狀態(tài):關(guān)閉
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" })
}
});
}
//關(guān)閉成功后開啟搜索
function stopSearchBeacom() {
wx.stopBeaconDiscovery({
success: function () {
searchBeacon();
}
})
}
},
介紹小程序的頁面生命周期函數(shù)之一:onShow
監(jiān)聽頁面顯示:即每次打開頁面都會調(diào)用一次。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
js創(chuàng)建一個input數(shù)組并綁定click事件的方法
這篇文章主要介紹了js創(chuàng)建一個input數(shù)組并綁定click事件的方法,需要的朋友可以參考下2014-06-06

