使用uniapp自带的低功耗蓝牙传数据,安卓最好不能超过20个字节(ios可以不限制字节大小),我传的数据较长,有几千个字节,ios倒是能一下就传过去,挺省事的。主要是安卓,非要用uniapp低功耗蓝牙传的话需要循环调用writeBLECharacteristicValue写入数据,要二十几秒才能传完,时间太长了。所以优化只能选择经典蓝牙。
我试了插件市场上面的很多经典蓝牙,选择了Android经典蓝牙插件,(ios不支持经典蓝牙,所以如果是ios系统就用低功耗蓝牙,安卓系统就用经典蓝牙)
handleBlue(){
this.platform = uni.getSystemInfoSync().platform
if (this.platform == 'ios') {
// ios
this.handleIosBlue()
} else {
// 安卓
this.handleIosBlue()
}
},
// 打开ios ble蓝牙
handleIosBlue() {
uni.openBluetoothAdapter({
success: (res) => {
uni.startBluetoothDevicesDiscovery({
success: (res) => {
console.log('搜索设备---', res)
uni.onBluetoothDeviceFound((devices) => {
if (devices.devices[0].name) {
if (this.blueList.findIndex((v) => v.deviceId == devices.devices[0].deviceId) == -1) {
this.blueList = this.blueList.concat(devices.devices[0])
}
}
})
},
})
},
fail: function(msg) {
uni.$u.toast('请先打开蓝牙')
}
})
},
// 打开安卓经典蓝牙
handleAndroidBlue() {
this.blueList = []
blueModule.openBT((ret) => {
blueModule.searchBT((ret1) => {
const temp = ret1.data
if (temp && temp.name) {
if (this.blueList.findIndex((v) => v.address == temp.address) == -1) {
this.blueList = this.blueList.concat(temp)
}
}
});
});
},