UniAPP传统蓝牙
UniAPP 传统蓝牙开发指南
UniAPP 支持通过传统蓝牙(Classic Bluetooth)进行设备通信,适用于需要与蓝牙外设(如打印机、POS机等)交互的场景。以下是关键实现方法和注意事项:
初始化蓝牙模块
在 onLoad 或页面初始化时调用 openBluetoothAdapter 开启蓝牙模块:
uni.openBluetoothAdapter({
success(res) {
console.log('蓝牙模块初始化成功');
},
fail(err) {
console.error('初始化失败:', err);
}
});
搜索附近蓝牙设备
通过 startBluetoothDevicesDiscovery 开始搜索,监听 onBluetoothDeviceFound 获取设备列表:
uni.startBluetoothDevicesDiscovery({
services: ['00001101-0000-1000-8000-00805F9B34FB'], // 常用SPP服务UUID
success(res) {
uni.onBluetoothDeviceFound(foundDevices => {
console.log('发现设备:', foundDevices.devices);
});
}
});
连接目标设备
使用 createBLEConnection 建立连接,需指定设备ID:
uni.createBLEConnection({
deviceId: '目标设备ID',
success(res) {
console.log('连接成功');
}
});
数据读写操作
发送数据
通过 writeBLECharacteristicValue 发送指令:
const buffer = new ArrayBuffer(8);
const dataView = new DataView(buffer);
dataView.setUint8(0, 0x01); // 示例指令
uni.writeBLECharacteristicValue({
deviceId,
serviceId,
characteristicId,
value: buffer,
success() {
console.log('写入成功');
}
});
接收数据
监听 onBLECharacteristicValueChange:
uni.onBLECharacteristicValueChange(res => {
const value = new Uint8Array(res.value);
console.log('收到数据:', value);
});
断开连接与释放资源
操作完成后需主动断开连接并关闭适配器:
uni.closeBLEConnection({ deviceId });
uni.closeBluetoothAdapter();
兼容性说明
-
平台差异
- Android 需声明蓝牙权限:
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> - iOS 需在
manifest.json中添加bluetooth权限声明。
- Android 需声明蓝牙权限:
-
服务UUID
传统蓝牙通常使用 SPP 协议,标准UUID为00001101-0000-1000-8000-00805F9B34FB。
常见问题处理
-
搜索不到设备
检查设备是否处于可发现模式,Android 需开启位置权限。 -
连接失败
确认设备ID和服务UUID是否正确,部分设备需要配对后才能连接。 -
数据传输异常
确保数据格式符合设备协议要求,建议使用十六进制调试工具分析。
通过以上步骤可实现UniAPP与传统蓝牙设备的基本交互,实际开发中需根据具体设备协议调整数据格式和处理逻辑。






