微信小程序实现搜索周边蓝牙并且返回蓝牙列表代码
时间: 2024-01-21 16:17:36 浏览: 20
以下是微信小程序搜索周围蓝牙并返回蓝牙列表的代码示例。
1. 在小程序页面的js文件,需要引入wx.createBLEConnection()和wx.onBluetoothDeviceFound()两个API:
```
//index.js
Page({
data: {
devices: [] //用于存储搜索到的蓝牙设备
},
//搜索蓝牙设备
searchBluetooth(e) {
wx.openBluetoothAdapter({ //初始化蓝牙模块
success: (res) => {
wx.startBluetoothDevicesDiscovery({ //开始搜索蓝牙设备
services: [],
allowDuplicatesKey: false,
success: (res) => {
console.log('startBluetoothDevicesDiscovery', res);
//监听寻找到新设备的事件
wx.onBluetoothDeviceFound((res) => {
const devices = this.data.devices
devices.push(res.devices[0])
this.setData({
devices: devices
})
})
}
})
},
fail: (res) => {
console.log('openBluetoothAdapter', res);
}
})
}
})
```
2. 在小程序页面的wxml文件中,需要添加一个按钮,点击按钮可以触发搜索蓝牙设备的函数:
```
<!--index.wxml-->
<view class="container">
<button type="primary" bindtap="searchBluetooth">搜索蓝牙设备</button>
<view class="devices">
<view wx:for="{{devices}}">
<text>设备名称:{{item.name}}</text>
<text>设备ID:{{item.deviceId}}</text>
</view>
</view>
</view>
```
3. 在小程序页面的wxss文件中,可以添加一些样式来美化页面:
```
/*index.wxss*/
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
}
.devices {
margin-top: 20px;
}
```
以上就是搜索周围蓝牙并返回蓝牙列表的微信小程序代码示例。