HarmonyOS DeviceUtil 深度解析(三):电池信息全攻略
文章目录一、前言二、工具函数方法速览三、方法逐一详解3.1 getBatterySOC() — 获取剩余电量3.2 getBatteryCapacityLevel() — 获取电量等级3.3 getHealthStatus() — 获取电池健康状态3.4 getBatteryTemperature() — 获取电池温度3.5 getVoltage() — 获取电池电压3.6 getNowCurrent() — 获取当前电流四、完整演示代码五、实际应用场景场景 1低电量警告场景 2电池过热保护场景 3充电状态检测六、注意事项七、小结一、前言近期发现一款很有意思的HarmonyOS 三方库, 地址 pura/harmony-utils(V1.4.0) , 作者是桃花镇童长老, 我这里也是直接通过该作者公布的源码进行案例编写进行,写了到目前写了一部分demo ,感觉确实很有帮助,这里呢也是开始写一个系列的演示demo 供大家参考。如有帮助可以在OpenHarmony中进行下载安装进行使用哦案例demo导航展示↓↓↓↓↓↓接下来言归正传 ↓↓↓↓手机 App 经常需要关注设备电池状态——比如在电量极低时暂停后台任务、在过热时降低计算强度、在充电时触发特定逻辑。HarmonyOS 提供了完整的batteryInfo模块而DeviceUtil对其进行了统一封装让你无需关心底层细节直接调用简洁的静态方法即可获取所有电池数据。本文将带你逐一了解DeviceUtil中的电池相关方法并结合DeviceUtilDemoPage.ets中的演示代码理解每个方法的返回值含义和实际应用场景。二、工具函数方法速览DeviceUtil.ets中电池相关的方法共 6 个// 获取剩余电量百分比0~100staticgetBatterySOC():number// 获取电量等级枚举满电/高/正常/低/告警/极低/关机staticgetBatteryCapacityLevel():batteryInfo.BatteryCapacityLevel// 获取健康状态枚举未知/正常/过热/过压/低温/僵死staticgetHealthStatus():batteryInfo.BatteryHealthState// 获取电池温度单位 0.1°C如 350 35.0°CstaticgetBatteryTemperature():number// 获取电池电压单位微伏如 3800000 3.8VstaticgetVoltage():number// 获取当前电流单位毫安充电为正放电为负staticgetNowCurrent():number三、方法逐一详解3.1getBatterySOC()— 获取剩余电量源码staticgetBatterySOC():number{returnbatteryInfo.batterySOC;}说明直接读取batteryInfo.batterySOC返回0~100的整数代表当前剩余电量百分比。Demo 演示loadBattery(){constsocDeviceUtil.getBatterySOC();this.batterySocResult${soc}%;// ...}界面显示效果Demo 中用颜色区分电量高低——电量 50% 显示绿色10%~50% 显示橙色 20% 显示红色Text(this.batterySocResult).fontSize(32).fontWeight(FontWeight.Bold).fontColor(Number(this.batterySocResult.replace(%,))50?#00C853:Number(this.batterySocResult.replace(%,))20?#FF9800:#FF5252)3.2getBatteryCapacityLevel()— 获取电量等级源码staticgetBatteryCapacityLevel():batteryInfo.BatteryCapacityLevel{returnbatteryInfo.batteryCapacityLevel;}枚举值说明枚举值数字含义LEVEL_FULL1满电量LEVEL_HIGH2高电量LEVEL_NORMAL3正常电量LEVEL_LOW4低电量LEVEL_WARNING5告警电量LEVEL_CRITICAL6极低电量LEVEL_SHUTDOWN7关机电量Demo 中的枚举转换getBatteryLevelLabel(level:batteryInfo.BatteryCapacityLevel):string{switch(level){casebatteryInfo.BatteryCapacityLevel.LEVEL_FULL:return满电;casebatteryInfo.BatteryCapacityLevel.LEVEL_HIGH:return高电量;casebatteryInfo.BatteryCapacityLevel.LEVEL_NORMAL:return正常;casebatteryInfo.BatteryCapacityLevel.LEVEL_LOW:return低电量;casebatteryInfo.BatteryCapacityLevel.LEVEL_WARNING:return告警;casebatteryInfo.BatteryCapacityLevel.LEVEL_CRITICAL:return极低;casebatteryInfo.BatteryCapacityLevel.LEVEL_SHUTDOWN:return关机;default:return未知;}}使用constlevelDeviceUtil.getBatteryCapacityLevel();this.batteryLevelResultthis.getBatteryLevelLabel(level);3.3getHealthStatus()— 获取电池健康状态源码staticgetHealthStatus():batteryInfo.BatteryHealthState{returnbatteryInfo.healthStatus;}枚举值说明枚举值数字含义UNKNOWN0未知GOOD1正常OVERHEAT2过热OVERVOLTAGE3过压COLD4低温DEAD5僵死状态Demo 中的枚举转换getHealthLabel(state:batteryInfo.BatteryHealthState):string{switch(state){casebatteryInfo.BatteryHealthState.UNKNOWN:return未知;casebatteryInfo.BatteryHealthState.GOOD:return正常;casebatteryInfo.BatteryHealthState.OVERHEAT:return过热;casebatteryInfo.BatteryHealthState.OVERVOLTAGE:return过压;casebatteryInfo.BatteryHealthState.COLD:return低温;casebatteryInfo.BatteryHealthState.DEAD:return僵死;default:return未知;}}使用consthealthDeviceUtil.getHealthStatus();this.healthStatusResultthis.getHealthLabel(health);注意当健康状态不是GOOD时通常意味着电池需要更换或当前环境温度异常应用可以在此时给用户提示。3.4getBatteryTemperature()— 获取电池温度源码staticgetBatteryTemperature():number{returnbatteryInfo.batteryTemperature;}说明返回值单位是0.1 摄氏度即实际温度 × 10。例如返回350代表35.0°C。Demo 中的单位换算this.temperatureResult${(DeviceUtil.getBatteryTemperature()/10).toFixed(1)}°C;3.5getVoltage()— 获取电池电压源码staticgetVoltage():number{returnbatteryInfo.voltage;}说明返回值单位是微伏μV需要除以 1,000,000 得到伏特V。例如返回3800000代表3.8V。Demo 中的单位换算this.voltageResult${(DeviceUtil.getVoltage()/1000000).toFixed(2)}V;3.6getNowCurrent()— 获取当前电流源码staticgetNowCurrent():number{returnbatteryInfo.nowCurrent;}说明返回值单位是毫安mA。充电时为正值放电时为负值部分设备可能总是正值取决于厂商实现。Demo 中的使用this.currentResult${DeviceUtil.getNowCurrent()}mA;四、完整演示代码DeviceUtilDemoPage.ets中电池部分的完整代码如下// ── 电池 ─────────────────────────────────────────────loadBattery(){constsocDeviceUtil.getBatterySOC();this.batterySocResult${soc}%;constlevelDeviceUtil.getBatteryCapacityLevel();this.batteryLevelResultthis.getBatteryLevelLabel(level);consthealthDeviceUtil.getHealthStatus();this.healthStatusResultthis.getHealthLabel(health);this.temperatureResult${(DeviceUtil.getBatteryTemperature()/10).toFixed(1)}°C;this.voltageResult${(DeviceUtil.getVoltage()/1000000).toFixed(2)}V;this.currentResult${DeviceUtil.getNowCurrent()}mA;this.addLog(Battery,电量:${this.batterySocResult}, 状态:${this.healthStatusResult},info);}UI 部分展示了电量、等级、健康状态、温度、电压、电流的可视化卡片并有刷新按钮// 电池状态Column(){Text(电池状态).fontSize(13).fontColor(#666).fontWeight(FontWeight.Medium).alignSelf(ItemAlign.Start).margin({bottom:10})// 电量环Row(){Column(){Text(this.batterySocResult).fontSize(32).fontWeight(FontWeight.Bold).fontColor(Number(this.batterySocResult.replace(%,))50?#00C853:Number(this.batterySocResult.replace(%,))20?#FF9800:#FF5252)Text(剩余电量).fontSize(11).fontColor(#888)}.layoutWeight(1).alignItems(HorizontalAlign.Center)Column(){Text(this.batteryLevelResult).fontSize(16).fontWeight(FontWeight.Bold).fontColor(#4080FF)Text(电量等级).fontSize(11).fontColor(#888)}.layoutWeight(1).alignItems(HorizontalAlign.Center)Column(){Text(this.healthStatusResult).fontSize(16).fontWeight(FontWeight.Bold).fontColor(this.healthStatusResult正常?#00C853:#FF9800)Text(健康状态).fontSize(11).fontColor(#888)}.layoutWeight(1).alignItems(HorizontalAlign.Center)}.width(100%).margin({bottom:10})// 详细信息Row(){Column(){Text(this.temperatureResult).fontSize(14).fontWeight(FontWeight.Bold).fontColor(#555)Text(电池温度).fontSize(10).fontColor(#888)}.layoutWeight(1).alignItems(HorizontalAlign.Center)Column(){Text(this.voltageResult).fontSize(14).fontWeight(FontWeight.Bold).fontColor(#555)Text(电池电压).fontSize(10).fontColor(#888)}.layoutWeight(1).alignItems(HorizontalAlign.Center)Column(){Text(this.currentResult).fontSize(14).fontWeight(FontWeight.Bold).fontColor(#555)Text(当前电流).fontSize(10).fontColor(#888)}.layoutWeight(1).alignItems(HorizontalAlign.Center)}.width(100%)Button(刷新电池信息).fontSize(12).height(34).margin({top:10}).backgroundColor(#4080FF).fontColor(#FFF).onClick((){this.loadBattery();})}.width(100%).padding(14).backgroundColor(#FFFFFF).borderRadius(12)五、实际应用场景场景 1低电量警告constsocDeviceUtil.getBatterySOC();if(soc20){// 提示用户充电promptAction.showToast({message:电量不足${soc}%请及时充电});}场景 2电池过热保护consttempDeviceUtil.getBatteryTemperature()/10;// 转换为摄氏度if(temp45){// 暂停高耗能操作this.stopHeavyTask();}场景 3充电状态检测constcurrentDeviceUtil.getNowCurrent();constisChargingcurrent0;if(isCharging){// 充电中执行需要大量电量的任务this.runBatchSync();}六、注意事项单位换算温度要除以 10电压要除以 1,000,000不要直接使用原始值展示给用户。实时性batteryInfo是时间点的快照不会自动更新需要定时刷新或监听系统广播。电流方向不同设备厂商对电流正负方向的定义可能不同需要实际测试验证。健康状态非 GOOD在生产环境中需谨慎处理避免在异常状态下执行高负载任务。七、小结方法返回类型单位说明getBatterySOC()number%剩余电量 0~100getBatteryCapacityLevel()枚举-满电/高/正常/低/告警/极低/关机getHealthStatus()枚举-未知/正常/过热/过压/低温/僵死getBatteryTemperature()number0.1°C需除以 10getVoltage()numberμV需除以 1,000,000getNowCurrent()numbermA充电正/放电负掌握这 6 个方法可以让你的应用在关键时刻做出正确的电量管理决策提升用户体验和应用稳定性。