
鸿蒙跨设备电池状态监控系统 原创
鸿蒙跨设备电池状态监控系统
一、系统架构设计
基于HarmonyOS的分布式能力,我们设计了一个跨设备电池状态监控系统,可以实时获取并同步多设备的电池电量和充电状态。
!https://example.com/battery-monitor-arch.png
系统包含三大模块:
电池状态监控模块 - 使用@ohos.batteryInfo获取电池信息
分布式数据同步模块 - 通过@ohos.distributedData实现多设备状态同步
可视化界面模块 - 展示本机及同步设备的电池状态
二、核心代码实现
电池监控服务(ArkTS)
// BatteryService.ets
import batteryInfo from ‘@ohos.batteryInfo’;
import distributedData from ‘@ohos.distributedData’;
const BATTERY_SYNC_CHANNEL = ‘battery_status’;
class BatteryService {
private static instance: BatteryService = null;
private dataManager: distributedData.DataManager;
private listeners: BatteryListener[] = [];
@State batteryLevel: number = 100;
@State isCharging: boolean = false;
@State chargeType: number = batteryInfo.BatteryChargeType.NONE;
private constructor() {
this.initDataManager();
this.initBatteryMonitor();
public static getInstance(): BatteryService {
if (!BatteryService.instance) {
BatteryService.instance = new BatteryService();
return BatteryService.instance;
private initDataManager() {
this.dataManager = distributedData.createDataManager({
bundleName: 'com.example.batterymonitor',
area: distributedData.Area.GLOBAL
});
this.dataManager.registerDataListener(BATTERY_SYNC_CHANNEL, (data) => {
this.handleSyncData(data);
});
private initBatteryMonitor() {
// 初始状态
this.batteryLevel = batteryInfo.batterySOC;
this.isCharging = batteryInfo.isBatteryCharging;
this.chargeType = batteryInfo.chargeType;
// 监听电量变化
batteryInfo.on('batterySOCChange', (value: number) => {
this.batteryLevel = value;
this.notifyListeners();
this.syncBatteryStatus();
});
// 监听充电状态变化
batteryInfo.on('chargingStatusChange', (value: boolean) => {
this.isCharging = value;
this.notifyListeners();
this.syncBatteryStatus();
});
// 监听充电类型变化
batteryInfo.on('chargeTypeChange', (value: number) => {
this.chargeType = value;
this.notifyListeners();
this.syncBatteryStatus();
});
public getCurrentStatus(): BatteryStatus {
return {
level: this.batteryLevel,
isCharging: this.isCharging,
chargeType: this.chargeType,
timestamp: Date.now(),
deviceId: this.getDeviceId()
};
public addListener(listener: BatteryListener): void {
if (!this.listeners.includes(listener)) {
this.listeners.push(listener);
}
public removeListener(listener: BatteryListener): void {
this.listeners = this.listeners.filter(l => l !== listener);
private notifyListeners(): void {
const status = this.getCurrentStatus();
this.listeners.forEach(listener => {
listener.onBatteryChanged(status);
});
private syncBatteryStatus(): void {
const status = this.getCurrentStatus();
this.dataManager.syncData(BATTERY_SYNC_CHANNEL, status);
private handleSyncData(data: any): void {
if (data?.level ! undefined && data.deviceId ! this.getDeviceId()) {
const status: BatteryStatus = {
level: data.level,
isCharging: data.isCharging,
chargeType: data.chargeType,
timestamp: data.timestamp,
deviceId: data.deviceId
};
this.listeners.forEach(listener => {
listener.onRemoteBatteryChanged(status);
});
}
private getDeviceId(): string {
// 实际实现需要获取设备ID
return ‘local_device’;
}
interface BatteryStatus {
level: number;
isCharging: boolean;
chargeType: number;
timestamp: number;
deviceId: string;
interface BatteryListener {
onBatteryChanged(status: BatteryStatus): void;
onRemoteBatteryChanged(status: BatteryStatus): void;
export const batteryService = BatteryService.getInstance();
电池状态指示器组件(ArkUI)
// BatteryIndicator.ets
@Component
export struct BatteryIndicator {
@State level: number = 0;
@State isCharging: boolean = false;
@State chargeType: number = batteryInfo.BatteryChargeType.NONE;
@State deviceName: string = ‘本机’;
private deviceId?: string;
build() {
Column() {
// 设备名称
Text(this.deviceName)
.fontSize(16)
.margin({ bottom: 8 })
// 电池图标
Stack() {
// 电池外框
Rect()
.width(40)
.height(20)
.borderRadius(2)
.borderWidth(1)
.borderColor('#333333')
// 电池正极
Rect()
.width(3)
.height(5)
.borderRadius(1)
.backgroundColor('#333333')
.position({ x: 43, y: 7.5 })
// 电量填充
Rect()
.width(36 * (this.level / 100))
.height(16)
.borderRadius(1)
.backgroundColor(this.getBatteryColor())
.position({ x: 2, y: 2 })
// 充电图标
if (this.isCharging) {
Image($r('app.media.ic_charging'))
.width(16)
.height(16)
.position({ x: 12, y: 2 })
}
.width(46)
.height(24)
// 电量文本
Text(${this.level}%)
.fontSize(14)
.margin({ top: 4 })
// 充电状态
if (this.isCharging) {
Text(this.getChargeTypeText())
.fontSize(12)
.margin({ top: 2 })
}
.padding(12)
.backgroundColor('#F5F5F5')
.borderRadius(8)
private getBatteryColor(): Color {
if (this.isCharging) return Color.Green;
if (this.level < 20) return Color.Red;
if (this.level < 50) return Color.Orange;
return Color.Black;
private getChargeTypeText(): string {
switch (this.chargeType) {
case batteryInfo.BatteryChargeType.AC_CHARGER:
return '交流充电';
case batteryInfo.BatteryChargeType.USB_CHARGER:
return 'USB充电';
case batteryInfo.BatteryChargeType.WIRELESS_CHARGER:
return '无线充电';
default:
return '充电中';
}
public setStatus(status: BatteryStatus): void {
this.level = status.level;
this.isCharging = status.isCharging;
this.chargeType = status.chargeType;
this.deviceId = status.deviceId;
this.deviceName = status.deviceId === batteryService.getCurrentStatus().deviceId ?
‘本机’ : 设备 ${status.deviceId.slice(-4)};
}
多设备电池监控面板(ArkUI)
// BatteryDashboard.ets
@Entry
@Component
struct BatteryDashboard {
@State localBattery: BatteryStatus = {
level: 0,
isCharging: false,
chargeType: batteryInfo.BatteryChargeType.NONE,
timestamp: 0,
deviceId: ‘’
};
@State remoteBatteries: Map<string, BatteryStatus> = new Map();
private batteryListener: BatteryListener = {
onBatteryChanged: (status) => {
this.localBattery = status;
},
onRemoteBatteryChanged: (status) => {
this.remoteBatteries.set(status.deviceId, status);
};
aboutToAppear() {
batteryService.addListener(this.batteryListener);
this.localBattery = batteryService.getCurrentStatus();
aboutToDisappear() {
batteryService.removeListener(this.batteryListener);
build() {
Column() {
// 标题
Text('多设备电池状态')
.fontSize(20)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 20 })
// 本机电池状态
BatteryIndicator()
.setStatus(this.localBattery)
.margin({ bottom: 20 })
// 其他设备电池状态
if (this.remoteBatteries.size > 0) {
Text('其他设备')
.fontSize(16)
.margin({ bottom: 10 })
Grid() {
ForEach(Array.from(this.remoteBatteries.entries()), ([deviceId, status]) => {
GridItem() {
BatteryIndicator()
.setStatus(status)
})
.columnsTemplate(‘1fr 1fr’)
.rowsTemplate('1fr')
.columnsGap(15)
.rowsGap(15)
else {
Text('暂无其他设备数据')
.fontSize(14)
.margin({ top: 20 })
// 同步按钮
Button('同步所有设备')
.margin({ top: 20 })
.onClick(() => {
this.syncAllDevices();
})
.padding(20)
.width('100%')
.height('100%')
private syncAllDevices() {
// 触发所有设备同步电池状态
distributedData.sync(BATTERY_SYNC_CHANNEL, {
type: 'requestSync',
deviceId: this.localBattery.deviceId
});
}
三、项目配置
权限配置
// module.json5
“module”: {
"requestPermissions": [
“name”: “ohos.permission.BATTERY_STATS”,
"reason": "获取电池状态信息"
},
“name”: “ohos.permission.DISTRIBUTED_DATASYNC”,
"reason": "跨设备同步电池状态"
],
"abilities": [
“name”: “MainAbility”,
"type": "page",
"visible": true
],
"distributedNotification": {
"scenarios": [
“name”: “battery_monitor”,
"value": "battery_status"
]
}
资源文件
<!-- resources/base/element/string.json -->
“string”: [
“name”: “app_name”,
"value": "电池监控"
},
“name”: “dashboard_title”,
"value": "多设备电池状态"
},
“name”: “local_device”,
"value": "本机"
},
“name”: “remote_devices”,
"value": "其他设备"
},
“name”: “no_devices”,
"value": "暂无其他设备数据"
},
“name”: “sync_button”,
"value": "同步所有设备"
},
“name”: “ac_charging”,
"value": "交流充电"
},
“name”: “usb_charging”,
"value": "USB充电"
},
“name”: “wireless_charging”,
"value": "无线充电"
},
“name”: “charging”,
"value": "充电中"
]
四、功能扩展
低电量预警功能
// 在BatteryService中添加
class BatteryService {
private lowBatteryThreshold: number = 20;
private warnedDevices: Set<string> = new Set();
private notifyListeners(): void {
const status = this.getCurrentStatus();
// 低电量预警
if (status.level <= this.lowBatteryThreshold &&
!this.warnedDevices.has(status.deviceId)) {
this.showLowBatteryAlert(status);
this.warnedDevices.add(status.deviceId);
else if (status.level > this.lowBatteryThreshold) {
this.warnedDevices.delete(status.deviceId);
this.listeners.forEach(listener => {
listener.onBatteryChanged(status);
});
private showLowBatteryAlert(status: BatteryStatus): void {
promptAction.showToast({
message: 设备电量低 (${status.level}%),
duration: 3000
});
// 同步预警到其他设备
this.dataManager.syncData(BATTERY_SYNC_CHANNEL, {
type: 'lowBatteryAlert',
deviceId: status.deviceId,
level: status.level,
timestamp: Date.now()
});
}
电池健康状态监测
// 扩展BatteryStatus接口
interface BatteryStatus {
health?: batteryInfo.BatteryHealthState;
temperature?: number;
voltage?: number;
// 在BatteryIndicator组件中添加
@Component
export struct BatteryIndicator {
@Builder
buildHealthInfo() {
if (this.health) {
Column() {
Text(健康: ${this.getHealthText()})
.fontSize(12)
if (this.temperature) {
Text(温度: ${this.temperature}°C)
.fontSize(12)
.margin({ top: 2 })
if (this.voltage) {
Text(电压: ${this.voltage}mV)
.fontSize(12)
.margin({ top: 2 })
}
.margin({ top: 8 })
}
private getHealthText(): string {
switch (this.health) {
case batteryInfo.BatteryHealthState.GOOD:
return ‘良好’;
case batteryInfo.BatteryHealthState.OVERHEAT:
return ‘过热’;
case batteryInfo.BatteryHealthState.OVERVOLTAGE:
return ‘过压’;
case batteryInfo.BatteryHealthState.COLD:
return ‘过冷’;
case batteryInfo.BatteryHealthState.DEAD:
return ‘损坏’;
default:
return ‘未知’;
}
五、总结
本系统实现了以下功能:
实时监控本机电池状态(电量、充电状态、充电类型)
通过分布式能力同步多设备电池状态
可视化展示电池状态信息
低电量预警功能
电池健康状态监测
系统特点:
响应式设计,实时更新状态
跨设备数据同步,统一管理
可扩展性强,方便添加新功能
界面友好,直观展示信息
通过这个系统,用户可以方便地监控自己和关联设备的电池状态,及时做出相应调整,提升多设备使用体验。
