Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Cordova battery status


May 21, 2021 Cordova


Table of contents


The Cordova plug-in is used to monitor the battery status of the device. /b10> The plug-in monitors every change in the device's battery.

Step 1 - Install the battery plug-in

To install this plug-in, we need to open the command prompt window and run the following code.

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

Step 2 - Add an event listener

When you open .js index file, you will find the onDeviceReady function. /b10> This is where event listeners should be added.

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

Step 3 - Create a callback function

We'll .js onBatteryStatus callback function at the bottom of the index file.

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

When we run the application, an alert is triggered. /b10> At this point the battery is 100% charged.

When the status changes, we are notified of the new alert. /b10> The battery status is now 99% charged.

Cordova battery status

If we plug the device into the charger, a new reminder will show that the isPlugged value has been changed to true.

Cordova battery status

Other events

This plug-in also provides two events in addition to batterystatus. /b10> These events are used in the same way as batterystatus events.

Event Describe
batterylow This event is triggered when the battery charge percentage reaches a low value. /b10> This value varies from device to device.
batterycritical The event is triggered when the battery percentage reaches a critical value. /b10> This value varies from device to device.