npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@cordova-ohos/cordova-plugin-battery-status

v2.0.3

Published

Cordova Battery Status Plugin

Readme

cordova-plugin-battery-status

1. 插件介绍

cordova-plugin-battery-status 是一款专为 Cordova/PhoneGap 应用开发的电池状态监测插件,旨在帮助开发者实时获取设备的电池信息,包括电池电量、充电状态、电池健康度等关键数据。通过该插件,开发者无需关注不同操作系统对电池硬件的底层访问差异,即可通过简洁的 JavaScript API 实现电池状态监听功能,适用于需要根据电池状态调整应用行为的场景(如低电量时提示用户保存数据、充电时优化后台任务等),为用户提供更智能的应用体验。本文档主要介绍该插件在OHOS系统中的应用。

该插件完全遵循 Cordova 插件开发规范,支持多平台自适应,API 设计直观易用,可无缝集成到各类 Cordova 移动应用及桌面应用中。

2. 支持平台

该插件已针对以下操作系统和平台完成适配,确保电池状态监测功能的稳定性和数据准确性:

  • Android (API 级别 21 及以上,覆盖 Android 5.0 及更高版本)

  • iOS (iOS 10.0 及以上,支持 iPhone、iPad 等全系列 iOS 设备)

  • Windows (Windows 10 及以上,包含 UWP 通用应用场景)

  • Browser (主流桌面及移动浏览器,如 Chrome、Firefox、Edge、Safari)

  • Electron (Electron 11.0.0 及以上,支持 Windows、macOS、Linux 桌面平台)

  • OHOS (5.0+)

3. 安装步骤

3.1 前提条件

在安装插件前,请确保开发环境满足以下基础要求:

  1. 已安装 Node.js (v14.0.0 及以上) 和 npm (v6.0.0 及以上),可通过 node -vnpm -v 命令验证版本。

  2. 已全局安装 Cordova CLI (v10.0.0 及以上),若未安装,可执行以下命令:

npm install -g hcordova
  1. 已创建 Cordova 项目(若尚未创建,可通过 hcordova create MyBatteryApp com.example.batteryapp 电池状态示例应用 命令快速创建)。

3.2 插件安装命令

在 Cordova 项目根目录下,根据需求选择以下方式安装插件:

常用安装方法

通过 npm 仓库安装稳定版本,适合大多数开发场景:

#全平台安装
hcordova plugin add cordova-plugin-battery-status

#指定平台安装
hcordova plugin add cordova-plugin-battery-status --platform ohos

从 GitCode 源码安装

hcordova plugin add https://gitcode.com/OpenHarmony-Cordova/cordova-plugin-battery-status.git --platform ohos

安装指定版本

hcordova plugin add [email protected] --platform ohos

3.3 插件卸载命令

若需移除插件,在项目根目录执行以下命令:

#全平台卸载
hcordova plugin remove cordova-plugin-battery-status
#指定平台卸载
hcordova plugin remove cordova-plugin-battery-status --platform ohos

3.4 插件查看命令

安装完成后,可通过以下命令验证插件是否成功添加到项目中:

hcordova plugin list

若输出结果包含 cordova-plugin-battery-status,则表示插件已成功安装。

4. 核心 API 说明

插件通过监听 batterystatusbatterylowbatterycritical 三种事件,实时获取设备电池状态信息,所有事件的回调函数均会接收一个包含电池详细数据的对象。以下是各 API 的详细说明:

4.1 监听电池状态变化(batterystatus)

batterystatus 事件在电池状态发生变化时触发(如电量增减、充电状态切换),是最核心的电池状态监听事件,可获取当前电池的实时数据。

事件回调参数

回调函数接收一个 status 对象,包含以下属性:

| 属性名 | 类型 | 说明 | | ----------------- | ------- | -------------------------------------------------------------------------- | | level | Number | 电池电量百分比(0-100),0 表示电量耗尽,100 表示电量满格。 | | isPlugged | Boolean | 充电状态标识,true 表示设备正在充电(有线充电、无线充电均会触发),false 表示未充电。 |

示例代码

// 等待 Cordova 环境就绪
document.addEventListener('deviceready', function() {
   // 监听电池状态变化事件
   document.addEventListener('batterystatus', function(status) {
       console.log('当前电池状态:', status);
       // 更新页面显示的电池电量
       document.getElementById('batteryLevel').textContent = `电量:${status.level}%`;
       // 更新充电状态显示
       const chargeStatus = status.isPlugged ? '正在充电' : '未充电';
       document.getElementById('chargeStatus').textContent = `充电状态:${chargeStatus}`;
       // 显示预计充电/放电时间(若支持)
       if (status.isPlugged && status.chargingTime !== null) {
           const hours = Math.floor(status.chargingTime / 3600);
           const minutes = Math.floor((status.chargingTime % 3600) / 60);
           document.getElementById('timeInfo').textContent = `预计充满时间:${hours}小时${minutes}分钟`;
       } else if (!status.isPlugged && status.dischargingTime !== null) {
           const hours = Math.floor(status.dischargingTime / 3600);
           const minutes = Math.floor((status.dischargingTime % 3600) / 60);
           document.getElementById('timeInfo').textContent = `预计剩余使用时间:${hours}小时${minutes}分钟`;
       } else {
           document.getElementById('timeInfo').textContent = '无法获取时间预估';
       }
   }, false);
}, false);

4.2 监听低电量状态(batterylow)

batterylow 事件在电池电量低于系统设定的 “低电量阈值” 时触发,适用于向用户发送低电量提醒(如提示保存数据、关闭高耗电功能)。

事件回调参数

回调函数接收的 status 对象与 batterystatus 事件一致,额外说明:

  • 触发阈值:OHOS 通常为 20%

示例代码

document.addEventListener('deviceready', function() {
   // 监听低电量事件
   document.addEventListener('batterylow', function(status) {
       console.log('低电量提醒:当前电量', status.level + '%');
       // 显示低电量弹窗提醒
       navigator.notification.alert(
           `当前电池电量较低(${status.level}%),建议及时充电,避免数据丢失。`,
           function() {
               // 点击确认后的逻辑,如关闭后台高耗电任务
               closeBackgroundTasks();
           },
           '低电量提醒',
           '知道了'
       );
   }, false);
}, false);

// 模拟关闭后台高耗电任务
function closeBackgroundTasks() {
   console.log('关闭后台高耗电任务...');
   // 实际项目中可添加关闭后台服务、降低屏幕亮度等逻辑
}

4.3 监听临界电量状态(batterycritical)

batterycritical 事件在电池电量低于系统设定的 “临界电量阈值” 时触发,适用于紧急场景(如自动保存所有数据、提示用户立即充电),若电量继续降低,设备可能很快关机。

事件回调参数

回调函数接收的 status 对象与 batterystatus 事件一致,额外说明:

  • 触发阈值:不同平台默认阈值不同(Android 通常为 5%,iOS 通常为 10%),系统级阈值不可通过插件修改。

示例代码

document.addEventListener('deviceready', function() {
   // 监听临界电量事件
   document.addEventListener('batterycritical', function(status) {
       console.log('临界电量警告:当前电量', status.level + '%');
       // 紧急处理逻辑:自动保存所有数据
       saveAllUserData().then(function() {
           // 显示临界电量警告弹窗
           navigator.notification.confirm(
               `当前电池电量已临界(${status.level}%),设备即将关机,请立即充电!`,
               function(buttonIndex) {
                   if (buttonIndex === 1) {
                       // 点击“立即充电”,可跳转至系统电池设置页面(部分平台支持)
                       if (cordova.platformId === 'android') {
                           cordova.plugins.settings.open('battery', function() {}, function() {});
                       }
                   }
               },
               '紧急电量警告',
               ['立即充电', '稍后']
           );
       });
   }, false);
}, false);

// 模拟自动保存所有用户数据
function saveAllUserData() {
   return new Promise(function(resolve) {
       console.log('正在自动保存用户数据...');
       // 实际项目中可添加本地存储、云端同步等逻辑
       setTimeout(resolve, 1000); // 模拟保存耗时
   });
}

4.4 移除事件监听

若无需继续监听电池状态,可通过 removeEventListener 方法移除事件监听,避免内存泄漏(尤其适用于单页应用切换页面时)。

示例代码

document.addEventListener('deviceready', function() {
   // 定义事件监听回调函数(需单独定义,以便后续移除)
   function onBatteryStatus(status) {
       console.log('电池状态:', status.level + '%');
   }
   // 添加事件监听
   document.addEventListener('batterystatus', onBatteryStatus, false);
   // 模拟页面跳转,移除事件监听
   document.getElementById('navigateBtn').addEventListener('click', function() {
       // 移除电池状态监听
       document.removeEventListener('batterystatus', onBatteryStatus, false);
       console.log('已移除电池状态监听');
       // 跳转至其他页面
       window.location.href = 'other-page.html';
   });
}, false);

5. 完整示例项目

以下是一个包含所有电池状态监听功能的完整 Cordova 页面示例,可直接复制到项目的 www/index.html 文件中使用:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
   <title>cordova-plugin-battery-status 示例</title>
   <style>
       body {
           font-family: Arial, sans-serif;
           padding: 20px;
           max-width: 600px;
           margin: 0 auto;
           background-color: #f5f5f5;
       }
      .battery-card {
           background-color: white;
           border-radius: 10px;
           padding: 25px;
           box-shadow: 0 2px 10px rgba(0,0,0,0.1);
           margin-bottom: 20px;
       }
       .battery-title {
           text-align: center;
           color: #333;
           margin-top: 0;
           margin-bottom: 20px;
       }

       .battery-info {
           font-size: 18px;
           margin: 15px 0;
           color: #555;
       }

       .battery-level {
           font-size: 24px;
           font-weight: bold;
           color: #2196F3;
           text-align: center;
           margin: 20px 0;
       }

       .charge-indicator {
           display: inline-block;
           width: 12px;
           height: 12px;
           border-radius: 50%;
           margin-right: 8px;
       }

       .charging {
           background-color: #4CAF50;
           animation: blink 1.5s infinite;
       }

       .not-charging {
           background-color: #F44336;
       }

       @keyframes blink {
           0% { opacity: 1; }
           50% { opacity: 0.5; }
           100% { opacity: 1; }
       }

       .btn {
           display: block;
           width: 100%;
           padding: 12px;
           margin-top: 15px;
           background-color: #2196F3;
           color: white;
           border: none;
           border-radius: 5px;
           font-size: 16px;
           cursor: pointer;
           transition: background-color 0.2s;
       }

       .btn:hover {
           background-color: #1976D2;
       }

       .note {
           font-size: 14px;
           color: #666;
           padding: 10px;
           background-color: #e8f4fd;
           border-radius: 5px;
           margin-top: 20px;
       }
   </style>

   <script type="text/javascript" src="cordova.js"></script>
   <script type="text/javascript">
       // 等待 Cordova 环境就绪
       document.addEventListener('deviceready', onDeviceReady, false);
       function onDeviceReady() {
           console.log('Cordova 环境已就绪,可监听电池状态');
           // 初始化页面显示
           document.getElementById('batteryLevel').textContent = '电量:获取中...';
           document.getElementById('chargeStatus').textContent = '充电状态:获取中...';
           document.getElementById('timeInfo').textContent = '时间预估:获取中...';
           
           // 监听电池状态变化
           document.addEventListener('batterystatus', updateBatteryInfo, false);
           
           // 监听低电量事件
           document.addEventListener('batterylow', showLowBatteryAlert, false);

           // 监听临界电量事件
           document.addEventListener('batterycritical', showCriticalBatteryAlert, false);

           // 绑定移除监听按钮事件
           document.getElementById('removeListenerBtn').addEventListener('click', function() {
               document.removeEventListener('batterystatus', updateBatteryInfo, false);
               document.removeEventListener('batterylow', showLowBatteryAlert, false);
               document.removeEventListener('batterycritical', showCriticalBatteryAlert, false);
               alert('已移除所有电池状态监听');
               this.disabled = true;
               this.textContent = '监听已移除';
           });
       }

       // 更新电池信息显示
       function updateBatteryInfo(status) {
           // 更新电量显示
           const levelText = `电量:${status.level}%`;
           document.getElementById('batteryLevel').textContent = levelText;
           document.getElementById('batteryLevel').style.color = getLevelColor(status.level);

          
           // 更新充电状态显示
           const chargeText = status.isPlugged ? '正在充电' : '未充电';
           const chargeIndicator = document.createElement('span');
           chargeIndicator.className = `charge-indicator ${status.isPlugged ? 'charging' : 'not-charging'}`;
           const chargeStatusElement = document.getElementById('chargeStatus');
           chargeStatusElement.innerHTML = '';
           chargeStatusElement.appendChild(chargeIndicator);
           chargeStatusElement.appendChild(document.createTextNode(`充电状态:${chargeText}`));

           // 更新时间预估显示
           let timeText = '无法获取时间预估';
           if (status.isPlugged && status.chargingTime !== null && status.chargingTime >= 0) {
               const hours = Math.floor(status.chargingTime / 3600);
               const minutes = Math.floor((status.chargingTime % 3600) / 60);
               timeText = `预计充满时间:${hours > 0 ? hours + '小时' : ''}${minutes}分钟`;
           } else if (!status.isPlugged && status.dischargingTime !== null && status.dischargingTime >= 0) {
               const hours = Math.floor(status.dischargingTime / 3600);
               const minutes = Math.floor((status.dischargingTime % 3600) / 60);
               timeText = `预计剩余使用时间:${hours > 0 ? hours + '小时' : ''}${minutes}分钟`;
           }

           document.getElementById('timeInfo').textContent = timeText;
       }

       // 根据电量获取显示颜色(绿色→黄色→红色)
       function getLevelColor(level) {
           if (level >= 60) return '#4CAF50'; // 绿色
           if (level >= 20) return '#FFC107'; // 黄色
           return '#F44336'; // 红色
       }

       // 显示低电量提醒
       function showLowBatteryAlert(status) {
           navigator.notification.alert(
               `当前电池电量较低(${status.level}%),建议及时充电,避免影响使用。`,
               function() {
                   // 降低屏幕亮度(仅 Android 支持,需额外插件)
                   if (cordova.platformId === 'android' && typeof cordova.plugins.brightness !== 'undefined') {
                       cordova.plugins.brightness.setBrightness(0.5);
                   }
               },
               '低电量提醒',
               '知道了'
           );
       }

       // 显示临界电量警告
       function showCriticalBatteryAlert(status) {
           // 自动保存数据
           saveUserData().then(function() {
               navigator.notification.confirm(
                   `紧急提醒:当前电池电量已不足${status.level}%,设备即将关机!请立即充电。`,
                   function(buttonIndex) {
                       if (buttonIndex === 1) {
                           // 跳转至系统电池设置页面(Android)
                           if (cordova.platformId === 'android') {
                               cordova.plugins.settings.open('battery', function() {}, function(err) {
                                   console.error('打开电池设置失败:', err);
                               });
                           }
                       }
                   },
                   '电池电量紧急警告',
                   ['立即充电', '稍后处理']
               );
           });
       }

       // 模拟保存用户数据
       function saveUserData() {
           return new Promise(function(resolve) {
               console.log('正在自动保存用户数据...');
               // 实际项目中可添加 localStorage 存储、API 同步等逻辑
               setTimeout(function() {
                   console.log('用户数据保存完成');
                   resolve();
               }, 800);
           });
       }
   </script>
</head>

<body>
   <div class="battery-card">
       <h1 class="battery-title">设备电池状态监测</h1>
       <div class="battery-level" id="batteryLevel">电量:获取中...</div>
       <div class="battery-info" id="chargeStatus">充电状态:获取中...</div>
       <div class="battery-info" id="timeInfo">时间预估:获取中...</div>
       <button id="removeListenerBtn" class="btn">移除电池状态监听</button>
   </div>

   <div class="note">
       <strong>注意事项:</strong><br>
       1. OHOS 无法获取完整的电池数据(如充电时间、放电时间)。<br>
       2. 电池电量更新频率由系统决定(通常为 1%-5% 电量变化时触发,或充电状态切换时触发)。<br>
       3. 若需获取屏幕亮度控制功能,需额外安装 `cordova-plugin-brightness` 插件。
   </div>

</body>

</html>

6. 许可证

本插件基于 Apache License 2.0 开源协议发布,详细许可条款请查看项目根目录下的 LICENSE 文件。

7. 联系方式与支持

若你在使用过程中遇到问题或有功能建议,可通过以下渠道获取支持:

OHOS

Android/iOS