需求:蓝牙搜索打印机并打印信息
微信小程序中需要打印订单信息
1.搜索打印机蓝牙,并链接
2.发送打印
微信小程序连接蓝牙
1.初始化蓝牙
1.1 wx.openBluetoothAdapter(Object object) :初始化蓝牙
1.2 wx.getBluetoothAdapterState():检测本机蓝牙是否可用
wx.openBluetoothAdapter({//初始化蓝牙
success: function (res) {
wx.getBluetoothAdapterState({//获取本机蓝牙适配器状态。
success: function (res) {
if (res.available) {//蓝牙适配器是否可用
//下一步操作
} else {
wx.showModal({
title: '提示',
content: '本机蓝牙不可用',
})
}
}
})
},
fail: function () {
wx.showModal({
title: '提示',
content: '蓝牙初始化失败,请打开蓝牙',
})
}
})
2.开始搜索蓝牙设备
2.1 wx.startBluetoothDevicesDiscovery() : 开始搜索蓝牙设备
2.2 wx.getBluetoothDevices():获取搜索到的蓝牙设备
wx.startBluetoothDevicesDiscovery({//搜索附近的蓝牙设备
services: [],//筛选过滤搜索的蓝牙设备
success(res) {
setTimeout(() => {
wx.getBluetoothDevices({//获取蓝牙列表
services: [],
success: function (res) {
callback(res);//返回蓝牙列表
},
fail(res) {
wx.showModal({
title: '提示',
content: '获取蓝牙设备列表失败',
})
}
})
}, 2000)
//关闭搜索
wx.stopBluetoothDevicesDiscovery({
success: function (res) {}
})
}
})
注:搜索完后要停止搜索