In the series of learning Apache Cordova, This article will tell you about how to install and use Battery plugin in your app. 

This Cordova plugin allows monitoring of battery status of the device. It will monitor and show each change that occurs when the battery is being used.

Step 1 - Battery Plugin Installation

To install the battery plugin, open command prompt window and execute the following code.

C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-battery-status  

Step 2 - Adding Event Listener

There is an onDeviceReady function inside the index.js file. This is where the event listener is to be added.

window.addEventListener("batterystatus", onBatteryStatus, false);

 

Step 3 - Create Callback Function

Now, you have to create onBatteryStatus callback function at the bottom of index.js file.

function onBatteryStatus(info)
{
   alert("BATTERY STATUS: Level: " + info.level + " isPlugged: " + info.isPlugged);
}

 

On running the app, alert will be triggered, when the battery is fully charged to 100%.

Once the battery status is changed, the new alert will be displayed. The battery status is now changes to 99%.

Cordova - Battery Plugin

Then, when you plug in the charger to the device, the new alert will display isPlugged value is set to true.


Cordova - Battery Plugin

Additional Events

This plugin also have additional two events besides batterystatus. These events can also be used in the same way as batterystatus event.

Event

Details

batterylow

This event is launched when battery charge percentage reached to a lower value. This value varies on different devices.

batterycritical

This event is launched when battery charge percentage reached to a critical value. This value also varies on different devices.

 

Also Read Previous Post: Event Handling In Apache Cordova

  Modified On Mar-19-2018 01:24:52 AM

Leave Comment