鸿蒙Next低能耗蓝牙通讯开发代码示例分享
在鸿蒙Next上进行低能耗蓝牙(BLE)通讯开发时,有没有具体的代码示例可以参考?想了解如何实现设备扫描、连接和数据传输的功能,最好能提供关键API的使用方法和注意事项。目前官方文档对实际应用场景的说明较少,希望有经验的朋友能分享下具体实现代码和常见问题解决方法。
2 回复
哈哈,想给鸿蒙Next的蓝牙省电?试试这个:
// 开启低功耗广播
BleAdvertiseSettings settings = new BleAdvertiseSettings.Builder()
.setConnectable(true)
.setInterval(BleAdvertiseSettings.INTERVAL_LOW) // 低间隔省电
.build();
// 记得用完关掉,不然电量像我的发际线一样消失
advertiser.stopAdvertising();
记住:少广播,多睡觉,蓝牙和你都需要美容觉!😴
更多关于鸿蒙Next低能耗蓝牙通讯开发代码示例分享的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
以下是鸿蒙Next(HarmonyOS NEXT)低功耗蓝牙(BLE)通信的代码示例,包括扫描、连接、读写特征值等核心步骤。示例基于ArkTS语言,适用于HarmonyOS应用开发。
1. 权限配置
首先在 module.json5 文件中添加蓝牙权限:
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.DISCOVER_BLUETOOTH",
"reason": "用于扫描蓝牙设备"
},
{
"name": "ohos.permission.MANAGE_BLUETOOTH",
"reason": "用于管理蓝牙连接"
},
{
"name": "ohos.permission.ACCESS_BLUETOOTH",
"reason": "用于访问蓝牙服务"
}
]
}
}
2. 核心代码示例
以下是一个简化的BLE通信类,包含扫描、连接和数据读写功能。
import ble from '@ohos.bluetooth.ble';
import { BusinessError } from '@ohos.base';
class BLEClient {
private deviceId: string = ''; // 存储连接的设备ID
private serviceUuid: string = '0000180F-0000-1000-8000-00805F9B34FB'; // 示例服务UUID(电池服务)
private characteristicUuid: string = '00002A19-0000-1000-8000-00805F9B34FB'; // 示例特征值UUID(电池级别)
// 扫描BLE设备
startScan(): void {
try {
ble.startBLEScan({
interval: 0, // 扫描间隔(毫秒)
dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER // 低功耗模式
});
console.log('开始扫描BLE设备...');
// 监听扫描结果
ble.on('BLEDeviceFind', (data: ble.BLEDeviceInfo) => {
console.log(`发现设备: ${data.deviceId}, 名称: ${data.deviceName}`);
// 可根据设备名称或UUID过滤目标设备
if (data.deviceName === '目标设备名') {
this.stopScan();
this.connectDevice(data.deviceId);
}
});
} catch (error) {
console.error(`扫描失败: ${(error as BusinessError).message}`);
}
}
// 停止扫描
stopScan(): void {
try {
ble.stopBLEScan();
console.log('停止扫描');
} catch (error) {
console.error(`停止扫描失败: ${(error as BusinessError).message}`);
}
}
// 连接设备
private connectDevice(deviceId: string): void {
try {
ble.connectBLEDevice({ deviceId });
this.deviceId = deviceId;
console.log(`连接设备: ${deviceId}`);
// 监听连接状态
ble.on('BLEConnectionStateChange', (data: ble.BLEConnectionChangeState) => {
if (data.deviceId === deviceId && data.state === ble.ProfileConnectionState.STATE_CONNECTED) {
console.log('设备连接成功');
this.discoverServices(); // 连接后发现服务
} else if (data.state === ble.ProfileConnectionState.STATE_DISCONNECTED) {
console.log('设备断开连接');
}
});
} catch (error) {
console.error(`连接失败: ${(error as BusinessError).message}`);
}
}
// 发现服务
private discoverServices(): void {
try {
ble.getBLEDeviceServices({ deviceId: this.deviceId }, (error, data) => {
if (error) {
console.error(`发现服务失败: ${error.message}`);
return;
}
console.log('发现服务列表:', data.services);
// 遍历服务,找到目标服务UUID
for (let service of data.services) {
if (service.serviceUuid === this.serviceUuid) {
this.discoverCharacteristics(service.serviceUuid);
}
}
});
} catch (error) {
console.error(`发现服务异常: ${(error as BusinessError).message}`);
}
}
// 发现特征值
private discoverCharacteristics(serviceUuid: string): void {
try {
ble.getBLEDeviceCharacteristics({
deviceId: this.deviceId,
serviceUuid: serviceUuid
}, (error, data) => {
if (error) {
console.error(`发现特征值失败: ${error.message}`);
return;
}
console.log('特征值列表:', data.characteristics);
// 找到目标特征值并读取数据
for (let char of data.characteristics) {
if (char.characteristicUuid === this.characteristicUuid) {
this.readCharacteristic(char.characteristicUuid);
}
}
});
} catch (error) {
console.error(`发现特征值异常: ${(error as BusinessError).message}`);
}
}
// 读取特征值数据
private readCharacteristic(characteristicUuid: string): void {
try {
ble.readBLECharacteristicValue({
deviceId: this.deviceId,
serviceUuid: this.serviceUuid,
characteristicUuid: characteristicUuid
}, (error, data) => {
if (error) {
console.error(`读取特征值失败: ${error.message}`);
return;
}
console.log(`特征值数据: ${data.value}`); // 输出十六进制数据
});
} catch (error) {
console.error(`读取特征值异常: ${(error as BusinessError).message}`);
}
}
// 写入特征值(示例:发送数据)
writeCharacteristic(data: Uint8Array): void {
try {
ble.writeBLECharacteristicValue({
deviceId: this.deviceId,
serviceUuid: this.serviceUuid,
characteristicUuid: this.characteristicUuid,
value: data
}, (error) => {
if (error) {
console.error(`写入特征值失败: ${error.message}`);
return;
}
console.log('数据写入成功');
});
} catch (error) {
console.error(`写入特征值异常: ${(error as BusinessError).message}`);
}
}
// 断开连接
disconnect(): void {
try {
if (this.deviceId) {
ble.disconnectBLEDevice({ deviceId: this.deviceId });
console.log('断开设备连接');
}
} catch (error) {
console.error(`断开连接失败: ${(error as BusinessError).message}`);
}
}
}
// 使用示例
let bleClient = new BLEClient();
bleClient.startScan(); // 启动扫描
// 在合适时机调用 bleClient.disconnect() 断开连接
关键说明:
- UUID配置:替换
serviceUuid和characteristicUuid为实际设备的UUID。 - 错误处理:所有操作需捕获
BusinessError,确保应用稳定性。 - 数据格式:读写数据时使用
Uint8Array处理二进制数据。 - 资源释放:在页面销毁时调用
disconnect()和stopScan()避免资源泄漏。
此示例覆盖了BLE通信的基本流程,可根据实际需求扩展通知监听、多服务处理等功能。开发时请参考鸿蒙官方BLE文档获取最新API。

