以下是鸿蒙Next(HarmonyOS NEXT)蓝牙BLE开发的关键步骤和示例代码,帮助你快速上手:
1. 权限配置
在 module.json5 中声明蓝牙权限:
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.DISCOVER_BLUTOOTH",
"reason": "扫描蓝牙设备"
},
{
"name": "ohos.permission.MANAGE_BLUTOOTH",
"reason": "管理蓝牙连接"
},
{
"name": "ohos.permission.LOCATION",
"reason": "获取设备位置(扫描必需)"
}
]
}
}
2. 初始化蓝牙适配器
import { bluetooth } from '@kit.ConnectivityKit';
// 检查蓝牙是否开启
async function enableBluetooth() {
try {
if (!bluetooth.getState()) {
await bluetooth.enable();
console.log('蓝牙已开启');
}
} catch (err) {
console.error('开启蓝牙失败:', err.code);
}
}
3. 扫描BLE设备
let scanner: bluetooth.BLEScanner;
// 开始扫描
async function startScan() {
scanner = bluetooth.createBLEScanner();
scanner.on('bluetoothDeviceFind', (devices: Array<bluetooth.BluetoothDevice>) => {
devices.forEach(device => {
console.log(`发现设备: ${device.deviceName}, MAC: ${device.deviceId}`);
});
});
await scanner.startScan();
console.log('开始扫描');
}
// 停止扫描
function stopScan() {
scanner.stopScan();
}
4. 连接设备与发现服务
let device: bluetooth.BLEDevice;
async function connect(deviceId: string) {
device = bluetooth.createBLE(deviceId);
// 监听连接状态
device.on('BLEConnectionStateChange', (state: boolean) => {
console.log(state ? '设备已连接' : '设备断开');
});
await device.connect();
const services = await device.getServices(); // 获取GATT服务
console.log('发现服务数量:', services.length);
}
5. 读写特征值
// 读取特征值
async function readCharacteristic(serviceUuid: string, charUuid: string) {
const value = await device.readCharacteristicValue(serviceUuid, charUuid);
console.log(`特征值: ${value}`);
}
// 写入特征值(需确认设备支持写入)
async function writeCharacteristic(serviceUuid: string, charUuid: string, data: Uint8Array) {
await device.writeCharacteristicValue(serviceUuid, charUuid, data);
}
// 订阅通知(监听设备数据推送)
async function subscribeNotify(serviceUuid: string, charUuid: string) {
device.on('BLECharacteristicChange', (characteristic: bluetooth.BLECharacteristic) => {
console.log('收到数据:', characteristic.value);
});
await device.setNotifyCharacteristicChanged(serviceUuid, charUuid, true);
}
6. 断开连接
function disconnect() {
device.disconnect();
device.off('BLEConnectionStateChange'); // 移除监听
}
关键注意事项
- 设备过滤:扫描时可通过
filters 按设备名或服务UUID过滤。
- 特征值权限:读写前检查特征的
properties 字段(如 readable、writeable)。
- 资源释放:页面销毁时需停止扫描并断开连接。
- 兼容性:鸿蒙Next API可能调整,请参考官方文档。
通过以上代码,你可以实现BLE设备的扫描、连接、数据读写等核心功能。建议结合具体设备协议(如心率仪、传感器)调整业务逻辑。