文章目录
- 一、前言
- 二、工具函数方法速览
- 三、方法逐一详解
- 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~100)staticgetBatterySOC():number// 获取电量等级枚举(满电/高/正常/低/告警/极低/关机)staticgetBatteryCapacityLevel():batteryInfo.BatteryCapacityLevel// 获取健康状态枚举(未知/正常/过热/过压/低温/僵死)staticgetHealthStatus():batteryInfo.BatteryHealthState// 获取电池温度(单位 0.1°C,如 350 = 35.0°C)staticgetBatteryTemperature():number// 获取电池电压(单位微伏,如 3800000 = 3.8V)staticgetVoltage():number// 获取当前电流(单位毫安,充电为正,放电为负)staticgetNowCurrent():number三、方法逐一详解
3.1getBatterySOC()— 获取剩余电量
源码:
staticgetBatterySOC():number{returnbatteryInfo.batterySOC;}说明:
直接读取batteryInfo.batterySOC,返回0~100的整数,代表当前剩余电量百分比。
Demo 演示:
loadBattery(){constsoc=DeviceUtil.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_FULL | 1 | 满电量 |
LEVEL_HIGH | 2 | 高电量 |
LEVEL_NORMAL | 3 | 正常电量 |
LEVEL_LOW | 4 | 低电量 |
LEVEL_WARNING | 5 | 告警电量 |
LEVEL_CRITICAL | 6 | 极低电量 |
LEVEL_SHUTDOWN | 7 | 关机电量 |
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'未知';}}使用:
constlevel=DeviceUtil.getBatteryCapacityLevel();this.batteryLevelResult=this.getBatteryLevelLabel(level);3.3getHealthStatus()— 获取电池健康状态
源码:
staticgetHealthStatus():batteryInfo.BatteryHealthState{returnbatteryInfo.healthStatus;}枚举值说明:
| 枚举值 | 数字 | 含义 |
|---|---|---|
UNKNOWN | 0 | 未知 |
GOOD | 1 | 正常 |
OVERHEAT | 2 | 过热 |
OVERVOLTAGE | 3 | 过压 |
COLD | 4 | 低温 |
DEAD | 5 | 僵死状态 |
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'未知';}}使用:
consthealth=DeviceUtil.getHealthStatus();this.healthStatusResult=this.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(){constsoc=DeviceUtil.getBatterySOC();this.batterySocResult=`${soc}%`;constlevel=DeviceUtil.getBatteryCapacityLevel();this.batteryLevelResult=this.getBatteryLevelLabel(level);consthealth=DeviceUtil.getHealthStatus();this.healthStatusResult=this.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:低电量警告
constsoc=DeviceUtil.getBatterySOC();if(soc<20){// 提示用户充电promptAction.showToast({message:`电量不足${soc}%,请及时充电`});}场景 2:电池过热保护
consttemp=DeviceUtil.getBatteryTemperature()/10;// 转换为摄氏度if(temp>45){// 暂停高耗能操作this.stopHeavyTask();}场景 3:充电状态检测
constcurrent=DeviceUtil.getNowCurrent();constisCharging=current>0;if(isCharging){// 充电中,执行需要大量电量的任务this.runBatchSync();}六、注意事项
- 单位换算:温度要除以 10,电压要除以 1,000,000,不要直接使用原始值展示给用户。
- 实时性:
batteryInfo是时间点的快照,不会自动更新,需要定时刷新或监听系统广播。 - 电流方向:不同设备厂商对电流正负方向的定义可能不同,需要实际测试验证。
- 健康状态非 GOOD:在生产环境中需谨慎处理,避免在异常状态下执行高负载任务。
七、小结
| 方法 | 返回类型 | 单位 | 说明 |
|---|---|---|---|
getBatterySOC() | number | % | 剩余电量 0~100 |
getBatteryCapacityLevel() | 枚举 | - | 满电/高/正常/低/告警/极低/关机 |
getHealthStatus() | 枚举 | - | 未知/正常/过热/过压/低温/僵死 |
getBatteryTemperature() | number | 0.1°C | 需除以 10 |
getVoltage() | number | μV | 需除以 1,000,000 |
getNowCurrent() | number | mA | 充电正/放电负 |
掌握这 6 个方法,可以让你的应用在关键时刻做出正确的电量管理决策,提升用户体验和应用稳定性。