PhoneGap Battery Status Plugin

Vishal Mishra
PhoneGap
Published in
2 min readMay 5, 2017

The PhoneGap Battery Status Plugin was released recently. This plugin serves a threefold purpose:

  1. It returns the battery status for Android and iOS devices.
  2. It conforms to the current W3C Battery Status API .
  3. It will be contributed to Apache Cordova once we have an implementation ready for Windows.

The method navigator.getBattery() returns a promise with a BatteryManager object which has the following properties and event handlers:

  • level: The battery charge level ranging from 0–1. (Number)
  • charging: A boolean that indicates whether the device is plugged in. (Boolean)
  • chargingTime: The time remaining to fully charge the battery. (Number)
  • dischargingTime: The time remaining for the battery level to come down to 0. (Number)
  • onchargingchange: This event fires when the device is plugged in or unplugged.
  • onchargingtimechange: This event fires when the time required to charge the device changes.
  • ondischargingtimechange: This event fires when the time that the device will take to discharge changes.
  • onlevelchange: A change in battery level fires this event.

An example usage of the onlevelchange event handler is shown below :

navigator.getBattery().then(function(battery) {
console.log(battery.level);
battery.onlevelchange = function() {
console.log(this.level);
};
});

The levelchange event type can be added to the battery object using the addEventListener object as shown below:

navigator.getBattery().then(function(battery) {
battery.addEventListener('levelchange', function() {
console.log(battery.level);
});
});

How to Install

The plugin can be installed by using the following command :

phonegap plugin add phonegap-plugin-battery-status

Issues

The chargingTime and the dischargingTime properties and the corresponding event handlers are, however, not supported on iOS.

Contact Us

Your feedback is graciously accepted and appreciated!
Please submit your pull requests and issues here.

--

--