微信小程序蓝牙 API教程完整版
1. 首先是要初始化蓝牙: openBluetoothAdapter()
if (wx.openBluetoothAdapter) {
wx.openBluetoothAdapter({
success: function(res) {
/ 获取本机的蓝牙状态 /
setTimeout(() => {
getBluetoothAdapterState()
}, 1000)
},
fail: function(err) {
// 初始化失败
}
})
} else {
}
2. 检测本机蓝牙是否可用:
初始化蓝牙成功之后回调里调用
getBluetoothAdapterState() {
var that = this;
that.toastTitle = '检查蓝牙状态'
wx.getBluetoothAdapterState({
success: function(res) {
startBluetoothDevicesDiscovery()
},
fail(res) {
console.log(res)
}
})
}
3. 开始搜索蓝牙设备:
startBluetoothDevicesDiscovery() {
var that = this;
setTimeout(() => {
wx.startBluetoothDevicesDiscovery({
success: function(res) {
/ 获取蓝牙设备列表 /
that.getBluetoothDevices()
},
fail(res) {
}
})
}, 1000)
}
4. 获取搜索到的蓝牙设备列表
/ that.deviceName 是获取到的蓝牙设备的名称, 因为蓝牙设备在安卓和苹果手机上搜到的蓝牙地址显示是不一样的, 所以根据设备名称匹配蓝牙 /
getBluetoothDevices() {
var that = this;
setTimeout(() => {
wx.getBluetoothDevices({
services: [],
allowDuplicatesKey: false,
interval: 0,
success: function(res) {
if (res.devices.length> 0) {
if (JSON.stringify(res.devices).indexOf(that.deviceName