微信小程序蓝牙 API教程完整版

微信小程序蓝牙 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
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值