May 21, 2021 Cordova
1. Step 1 - Install the battery plug-in
2. Step 2 - Add an event listener
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.
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
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);
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.
If we plug the device into the charger, a new reminder will show that the isPlugged value has been changed to true.
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. |