HTML5转APP之后是可以连接蓝牙设备的,核心实现依赖Web Bluetooth API标准,同时需要结合打包框架的原生能力适配,不同开发场景下的调用方式存在一定差异。
纯HTML5页面的蓝牙调用基础
如果是在支持Web Bluetooth API的浏览器环境中运行的HTML5页面,可以直接调用原生API实现蓝牙设备搜索、连接和数据交互,不需要额外的原生插件支持。
基础调用流程
Web Bluetooth API的核心调用步骤分为设备请求、连接、获取服务和特征值、数据读写四个部分,以下是基础示例代码:
// 请求蓝牙设备
async function connectBluetooth() {
try {
// 过滤目标蓝牙设备,这里以设备名称包含TestDevice为例
const device = await navigator.bluetooth.requestDevice({
filters: [{ namePrefix: 'TestDevice' }],
optionalServices: ['battery_service']
});
console.log('已选择设备:', device.name);
// 连接设备
const server = await device.gatt.connect();
console.log('设备连接成功');
// 获取目标服务
const service = await server.getPrimaryService('battery_service');
// 获取电量特征值
const characteristic = await service.getCharacteristic('battery_level');
// 读取电量数据
const value = await characteristic.readValue();
const batteryLevel = value.getUint8(0);
console.log('当前电量:', batteryLevel);
// 监听特征值变化
characteristic.addEventListener('characteristicvaluechanged', (event) => {
const newValue = event.target.value.getUint8(0);
console.log('电量更新:', newValue);
});
await characteristic.startNotifications();
} catch (error) {
console.error('蓝牙操作失败:', error);
}
}
注意事项
- Web Bluetooth API仅在HTTPS环境或者localhost本地环境中可用,普通HTTP页面无法调用
- 不同浏览器的支持程度不同,Chrome、Edge等Chromium内核浏览器支持较好,Safari的支持范围相对有限
- 调用
requestDevice方法时必须明确指定filters或者optionalServices,否则会直接报错
HTML5转APP的打包框架适配方法
将HTML5页面打包成APP时,需要根据使用的打包框架选择对应的适配方式,主流框架的适配逻辑如下。
Cordova/PhoneGap框架
Cordova本身没有内置蓝牙能力,需要安装第三方插件来实现蓝牙功能,常用的插件是cordova-plugin-ble-central,安装后可以在HTML5页面中直接调用插件提供的方法。
插件安装命令:
cordova plugin add cordova-plugin-ble-central
调用示例:
// 扫描蓝牙设备
function scanBluetooth() {
ble.scan([], 5, function(device) {
console.log('发现设备:', device.name, device.id);
}, function(error) {
console.error('扫描失败:', error);
});
}
// 连接指定设备
function connectDevice(deviceId) {
ble.connect(deviceId, function(peripheral) {
console.log('连接成功,设备服务:', peripheral.services);
// 读取特征值
ble.read(deviceId, '180F', '2A19', function(data) {
const battery = new Uint8Array(data)[0];
console.log('电量:', battery);
}, function(err) {
console.error('读取失败:', err);
});
}, function(error) {
console.error('连接失败:', error);
});
}
UniApp框架
UniApp提供了统一的蓝牙API,打包成APP后可以直接调用,不需要额外安装插件,API的使用方式和Web Bluetooth API类似,但是做了多端适配。
示例代码:
// 初始化蓝牙适配器
uni.openBluetoothAdapter({
success: function(res) {
console.log('蓝牙适配器初始化成功');
// 开始搜索设备
uni.startBluetoothDevicesDiscovery({
success: function(discoverRes) {
// 监听发现新设备
uni.onBluetoothDeviceFound(function(devices) {
console.log('发现设备:', devices.devices);
});
}
});
},
fail: function(err) {
console.error('初始化失败:', err);
}
});
// 连接设备
uni.createBLEConnection({
deviceId: '目标设备ID',
success: function(connRes) {
console.log('连接成功');
// 获取服务
uni.getBLEDeviceServices({
deviceId: '目标设备ID',
success: function(serviceRes) {
console.log('设备服务列表:', serviceRes.services);
}
});
}
});
React Native框架
React Native需要安装react-native-ble-plx插件来实现蓝牙功能,安装后可以在JS层调用蓝牙相关能力,插件的API设计更贴近原生开发逻辑。
安装命令:
npm install react-native-ble-plx
调用示例:
import { BleManager } from 'react-native-ble-plx';
const manager = new BleManager();
// 扫描设备
manager.startDeviceScan(null, null, (error, device) => {
if (error) {
console.error('扫描错误:', error);
return;
}
if (device.name && device.name.includes('TestDevice')) {
console.log('发现目标设备:', device.name);
manager.stopDeviceScan();
// 连接设备
device.connect().then((connectedDevice) => {
return connectedDevice.discoverAllServicesAndCharacteristics();
}).then((device) => {
console.log('设备服务发现完成');
}).catch((err) => {
console.error('连接失败:', err);
});
}
});
开发常见问题与解决方案
| 问题场景 | 解决方案 |
|---|---|
| 调用蓝牙API时提示无权限 | 在APP打包配置中添加蓝牙权限,Android需要添加<uses-permission android:name="android.permission.BLUETOOTH"/>和定位权限,iOS需要在info.plist中添加蓝牙使用描述 |
| 无法搜索到目标蓝牙设备 | 确认设备处于可被发现状态,检查过滤条件是否正确,安卓端需要确认定位权限已授予,因为安卓的蓝牙扫描依赖定位权限 |
| 连接后无法读取特征值 | 确认指定的服务和特征值UUID正确,部分设备需要先开启通知才能读取数据,或者需要先写入特定指令才能返回数据 |
总的来说,HTML5转APP后实现蓝牙设备连接是完全可行的,开发者只需要根据自己使用的打包框架选择对应的调用方式,同时注意权限配置和API的兼容性,就可以快速实现蓝牙相关的功能需求。
HTML5转APP蓝牙设备连接Web_Bluetooth_API蓝牙功能调用修改时间:2026-07-06 21:03:34