uni-app 搜索不到蓝牙设备
uni-app 搜索不到蓝牙设备
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Windows | 19043.1237 | HBuilderX |
产品分类
- uniapp/App
手机系统
- Android
手机系统版本号
- Android 13
手机厂商
- 台电
手机机型
- 安卓平板
页面类型
- vue
vue版本
- vue2
打包方式
- 云端
示例代码
constructor(SearchBluetoothCallback) {
this.SearchBluetoothCallback = SearchBluetoothCallback;
this.BleDeviceObjAry = []; //BleDevice对象数组
/*plus变量定义*/
this.main = null;
this.BluetoothAdapter = null;
this.BAdapter = null;
this.IntentFilter = null;
this.BluetoothDevice = null;
this.device = null,
this.uuid = null;
this.UUID = null;
this.outputStream;
this.inputStream;
//连接打印机和打印
this.bluetoothSocket;
this.receiver = null;
/*其他定义*/
this.isSearchDevices = false; //是否处于搜索状态
this.characterCacheArea = [];
this.printTimer = null; //打印定时器
//当前连接的设备ID(MAC 地址)
this.BluetoothMacAddress = "";
// 请求位置权限
this.ActivityCompat = null;
this.Manifest = null;
this.PackageManager = null;
this.enabledTimer = null; // 等待蓝牙开启timer
this.connectedLoading = false; // 连接中状态
}
//初始化方法
initBluetooth() {
// 获取权限
this.BleDeviceObjAry = [];
this.main = plus.android.runtimeMainActivity();
this.BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
this.IntentFilter = plus.android.importClass('android.content.IntentFilter');
this.BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
this.BAdapter = new this.BluetoothAdapter.getDefaultAdapter();
this.UUID = plus.android.importClass("java.util.UUID");
this.uuid = this.UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
this.requestPermission();
// this.CheckBluetoothState();
}
//连接到设备
connectBluetooth(deviceId, bleName, isbond) {
plus.storage.setItem("deviceId", deviceId);
if (isbond == 1) {
let self = this,
bdevice = new this.BluetoothDevice();
let id = deviceId,
state = true;
console.log(this.BleDeviceObjAry);
plus.nativeUI.showWaiting("正在配对...");
for (let i = 0; i < this.BleDeviceObjAry.length; i++) {
let BleDeviceItem = this.BleDeviceObjAry[i];
this.main.unregisterReceiver(this.receiver); //取消监听
if (BleDeviceItem.getAddress() === id) {
BleDeviceItem.createBond();
let testBondState = setInterval(() => {
if (BleDeviceItem.getBondState() === bdevice.BOND_BONDED) {
plus.nativeUI.closeWaiting();
mui.toast("配对成功");
var bleObj = new ConnectPrinter(id, bleName);
bleObj = null;
window.clearInterval(testBondState);
mui.back();
} else if (BleDeviceItem.getBondState() === bdevice.BOND_NONE) {
plus.nativeUI.closeWaiting();
mui.toast("配对失败");
window.clearInterval(testBondState);
} else {
plus.nativeUI.closeWaiting();
}
}, 1000);
state = false;
break;
}
}
if (state) {
plus.nativeUI.closeWaiting();
mui.toast("配对失败请重新搜索设备");
}
} else {
var bleObj = new ConnectPrinter(deviceId, bleName);
bleObj = null;
}
}
//检测蓝牙状态
CheckBluetoothState() {
let self = this;
if (!this.BAdapter.isEnabled()) {
plus.nativeUI.confirm("蓝牙处于关闭状态,是否打开?", (e) => {
console.log(e.index)
if (e.index == 0) {
// console.log(this.BAdapter.enable);
// 开启蓝牙
// plus.bluetooth.openBluetoothAdapter({
// success: () => {
// console.log("Bluetooth is enabled.");
// },
// fail: (error) => {
// console.log("Failed to enable Bluetooth:", error);
// }
// });
// console.log("蓝牙处于关闭状态,正在打开...");
let result = this.BAdapter.enable();
if (result == null) {
return uni.showToast({
icon: 'none',
title: '当前设备无法自动开启蓝牙,请手动开启蓝牙'
});
}
console.log(result);
self.SearchBluetoothDevices();
}
});
} else {
self.SearchBluetoothDevices();
console.log("蓝牙处于开启状态,准备搜索蓝牙设备...");
}
}
//停止搜搜
StopSearchBluetooth() {
console.log("停止蓝牙搜索...")
plus.nativeUI.closeWaiting();
if (this.BAdapter == null) return;
this.BAdapter.cancelDiscovery();
}
//搜索设备
SearchBluetoothDevices() {
console.log('进入开始蓝牙搜索');
try {
this.isSearchDevices = true;
//self.SetButtonStatus("正在搜索蓝牙设备...", true);
console.log("开始搜索蓝牙设备...");
let filter = new this.IntentFilter(),
bdevice = new this.BluetoothDevice();
this.BleDeviceObjAry = []; //清空BleDeviceObjAry
//unpairedList.innerHTML = '';
//pairedList.innerHTML = '';
this.BAdapter.startDiscovery(); //开启搜索
this.receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
onReceive: //监听回调函数
(context, intent) => {
console.log('搜索回调触发')
plus.android.importClass(intent); //通过intent实例引入intent类,方便以后的‘.’操作
//开始搜索改变状态
intent.getAction() === "android.bluetooth.device.action.FOUND" && (this.isSearchDevices = true);
//判断是否搜索结束
if (intent.getAction() === 'android.bluetooth.adapter.action.DISCOVERY_FINISHED') {
this.main.unregisterReceiver(this.receiver); //取消监听
this.isSearchDevices = false;
//self.SetButtonStatus("重新搜索设备", false);
return false;
}
let BleDevice = intent.getParcelableExtra(this.BluetoothDevice.EXTRA_DEVICE);
if (BleDevice == null) return false;
let name = BleDevice.getName(), //设备名称
deviceId = BleDevice.getAddress(); //设备mac地址
if (!name || !deviceId) {
return false;
}
// let sp = plus.webview.getWebviewById("html_print_selectPrinternew");
let bluetoothclass = BleDevice.getBluetoothClass();
console.log(JSON.stringify(bdevice));
plus.android.importClass(bluetoothclass);
let deviceType = bluetoothclass.getMajorDeviceClass();
//if (deviceType != 1536) return; //非打印机类型
//判断是否配对
if (BleDevice.getBondState() === bdevice.BOND_BONDED) {
typeof this.SearchBluetoothCallback === 'function' && this.SearchBluetoothCallback({
type: 1, // 1以配对 0未配对
name,
deviceId
});
console.log("已配对蓝牙设备:" + name + ' ' + deviceId);
BleDeviceObjAry.push(BleDevice);
} else {
typeof this.SearchBluetoothCallback === 'function' && this.SearchBluetoothCallback({
type: 0, // 1以配对 0未配对
name,
deviceId
});
console.log("未配对蓝牙设备:" + name + ' ' + deviceId);
BleDeviceObjAry.push(BleDevice);
}
}
});
filter.addAction(bdevice.ACTION_FOUND);
filter.addAction(this.BAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(this.BAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(this.BAdapter.ACTION_STATE_CHANGED);
this.main.registerReceiver(this.receiver, filter); //注册监听事件
} catch (e) {
console.log(e);
//TODO handle the exception
}
}
//创建蓝牙连接
createConnection(deviceId, name) {
this.BluetoothMacAddress = deviceId;
this.BluetoothMacName = name;
}
//自动连接上一次连接的打印机
AutoConnectLastPrinter() {
let last = plus.storage.getItem("lastconnectedprinter");
if (last == null) return;
last = JSON.parse(last);
//自动连接设备,不提示
ConnectPrinter(last.BluetoothMacAddress, last.BluetoothMacName, false);
}
print(mac_address, DATA) {
if (this.BAdapter == null) {
this.initBluetooth();
}
// 添加到缓存字节数组
let bytes = plus.android.invoke(DATA, 'getBytes', 'gbk');
console.log(bytes),
// let splitArrayBuffer = this.splitArrayBuffer(bytes, 1024);
this.characterCacheArea.push(bytes); // [...this.characterCacheArea, ...splitArrayBuffer];
if(this.connectedLoading) return;
this.connectedLoading = true;
return new Promise(async (resole, reject) => {
if (!this.BAdapter.isEnabled()) {
plus.nativeUI.confirm("蓝牙处于关闭状态,是否打开?", async (e) => {
console.log(e.index)
if (e.index == 0) {
console.log(this.BAdapter.enable);
// 开启蓝牙
// plus.bluetooth.openBluetoothAdapter({
// success: () => {
// console.log("Bluetooth is enabled.");
// },
// fail: (error) => {
// console.log("Failed to enable Bluetooth:", error);
// }
// });
console.log("蓝牙处于关闭状态,正在打开...");
let result = this.BAdapter.enable();
if (result == null) {
reject('当前设备无法自动开启蓝牙,请手动开启蓝牙');
this.connectedLoading = false;
return;
}
if (this.enabledTimer != null) clearInterval(this.enabledTimer);
this.enabledTimer = setInterval(async () => {
// 蓝牙已打开
if (this.BAdapter.isEnabled()) {
clearInterval(this.enabledTimer);
this.enabledTimer = null;
await this.sendPrint(mac_address);
resole();
}
}, 150);
}
});
} else {
await this.sendPrint(mac_address);
resole();
}
})
}
sendPrint(mac_address) {
uni.showLoading({
title: '打印中...'
})
return new Promise((resolve, reject) => {
try {
this.device = this.BAdapter.getRemoteDevice(mac_address);
console.log('进入打印6')
plus.android.importClass(this.device);
console.log('进入打印7')
this.bluetoothSocket = this.device.createInsecureRfcommSocketToServiceRecord(this.uuid);
console.log('进入打印8')
plus.android.importClass(this.bluetoothSocket);
if (!this.bluetoothSocket.isConnected()) {
console.log('连接蓝牙中....');
this.bluetoothSocket.connect();
}
if (this.bluetoothSocket.isConnected()) {
try {
console.log('进入打印')
let outputStream = this.bluetoothSocket.getOutputStream();
plus.android.importClass(outputStream);
// let string = DATA;
// let bytes = plus.android.invoke(string, 'getBytes', 'gbk');
// console.log(bytes.length,'打印长度')
if (this.printTimer !== null) return;
// 循环打印
this.printTimer = setInterval(() => {
if (this.characterCacheArea.length === 0) {
clearInterval(this.printTimer);
this.printTimer = null;
outputStream.flush();
this.device = null //这里关键
this.bluetoothSocket.close(); //必须关闭蓝牙连接否则意外断开的话打印错误
uni.hideLoading();
uni.showToast({
title: '打印成功',
icon: 'success'
})
this.connectedLoading = false;
resolve();
return;
// console.log(DATA)
}
console.log('传输数据');
console.log(this.bluetoothSocket.isConnected(), '蓝牙连接状态')
console.log(this.characterCacheArea[0]);
outputStream.write(this.characterCacheArea[0]);
this.characterCacheArea = this.characterCacheArea.filter((item, index) => index !== 0);
}, 1500);
} catch (e) {
this.connectedLoading = false;
reject(e);
console.log(e);
}
} else {
uni.showModal({
title: '系统提示',
content: '连接失败,请重新配置打印机',
success(res) {
if (res.confirm) {
uni.navigateTo({
url: '/pages/bluetoothtwo/bluetoothtwo'
})
}
}
})
this.connectedLoading = false;
reject();
}
} catch (e) {
this.connectedLoading = false;
reject(e);
//TODO handle the exception
}
})
}
//连接打印机
ConnectPrinter(deviceId, bleName) {
this.main = plus.android.runtimeMainActivity();
this.BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
this.UUID = plus.android.importClass("java.util.UUID");
this.uuid = this.UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
this.BAdapter = this.BluetoothAdapter.getDefaultAdapter();
this.device = this.BAdapter.getRemoteDevice(deviceId);
plus.android.importClass(this.device);
bluetoothSocket = this.device.createInsecureRfcommSocketToServiceRecord(this.uuid);
plus.android.importClass(this.bluetoothSocket);
if (!this.bluetoothSocket.isConnected()) {
console.log('检测到设备未连接,尝试连接....');
this.bluetoothSocket.connect();
}
console.log('设备已连接');
};
//关闭连接
ClosePrinter() {
//关闭连接
plus.IZMPrinter.Closeconnect((res) => {
this.inputStream = null;
this.outputStream = null;
this.bluetoothSocket = null;
this.BluetoothMacAddress = "";
// this.drawPrinterInfo("");
}, (res) => {});
}
//发送数据
sendPrintData() {
let bytes = plus.android.invoke(byteStr, 'getBytes', 'gbk');
this.outputStream.write(bytes);
this.outputStream.flush();
}
splitArrayBuffer(arrayBuffer, chunkSize) {
const buffer = new Uint8Array(arrayBuffer);
const result = [];
for (let i = 0; i < buffer.length; i += chunkSize) {
const chunk = buffer.slice(i, i + chunkSize);
const chunkArrayBuffer = chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength);
result.push(chunkArrayBuffer);
}
return result;
}
requestPermission() {
// 请求位置权限
this.ActivityCompat = plus.android.importClass("androidx.core.app.ActivityCompat");
this.Manifest = plus.android.importClass("android.Manifest");
this.PackageManager = plus.android.importClass("android.content.pm.PackageManager");
console.log('获取权限');
if (this.ActivityCompat.checkSelfPermission(this.main, this.Manifest.permission.ACCESS_FINE_LOCATION) !== this
.PackageManager.PERMISSION_GRANTED) {
this.ActivityCompat.requestPermissions(this.main, [this.Manifest.permission.ACCESS_FINE_LOCATION], 1);
}
if (this.ActivityCompat.checkSelfPermission(this.main, this.Manifest.permission.BLUETOOTH_CONNECT) !== this
.PackageManager.PERMISSION_GRANTED) {
this.ActivityCompat.requestPermissions(this.main, [this.Manifest.permission.BLUETOOTH_CONNECT], 1);
}
}
`
1 回复
在处理 uni-app
中搜索不到蓝牙设备的问题时,首先需要确保你的开发环境和设备配置是正确的。以下是一些常见的检查点和代码示例,帮助你排查和解决问题。
1. 权限检查
确保你的应用已经请求并获得了必要的蓝牙权限。在 manifest.json
中添加蓝牙权限:
"permissions": {
"scope.userLocation": {
"desc": "你的位置信息将用于蓝牙扫描"
},
"Bluetooth": {
"desc": "你的设备蓝牙将用于设备连接"
}
}
2. 初始化蓝牙适配器
在开始搜索之前,必须初始化蓝牙适配器。使用以下代码初始化蓝牙适配器:
uni.openBluetoothAdapter({
success: function (res) {
console.log('蓝牙适配器初始化成功', res)
// 开始搜索设备
startDiscoveryDevices();
},
fail: function (err) {
console.error('蓝牙适配器初始化失败', err)
}
});
3. 开始搜索设备
初始化成功后,调用 startBluetoothDevicesDiscovery
方法开始搜索设备:
function startDiscoveryDevices() {
uni.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
success: function (res) {
console.log('开始搜索蓝牙设备', res)
// 监听找到新设备的事件
uni.onBluetoothDeviceFound(function (devices) {
devices.devices.forEach(device => {
console.log('找到蓝牙设备:', device)
});
});
},
fail: function (err) {
console.error('搜索蓝牙设备失败', err)
}
});
}
4. 停止搜索设备
当不再需要搜索设备时,调用 stopBluetoothDevicesDiscovery
方法停止搜索:
uni.stopBluetoothDevicesDiscovery({
success: function (res) {
console.log('停止搜索蓝牙设备', res)
},
fail: function (err) {
console.error('停止搜索蓝牙设备失败', err)
}
});
5. 注意事项
- 确保你的设备蓝牙已经打开。
- 确保你的应用有权限访问蓝牙。
- 在某些设备上,蓝牙扫描可能需要用户授权或开启定位服务。
- 检查设备的蓝牙是否支持BLE(低功耗蓝牙),因为某些设备可能只支持经典蓝牙。
通过上述步骤和代码,你应该能够排查和解决 uni-app
中搜索不到蓝牙设备的问题。如果问题依旧存在,建议检查设备兼容性或查阅 uni-app
的官方文档和社区论坛获取更多帮助。