Phonegap Battery API tutorial | Apache Cordova Battery API

Phonegap / Apache Cordova battery api tutorials

Phonegap / Apache Cordova battery api tutorials

In this tutorials, I’m Going to teach how to get battery status using phonegap or apache cordova? 

By using phonegap / cordova battery plugin, we can access battery level (charge) and we can find whether mobile device is connected / plugged (charging) or not

Battery Events 

  • batterystatus    –  returns battery status
  • batterycritical   –  triggers when battery is critical
  • batterylow  –  triggers when battery is low

Battery Properties

  • level – will return battery level as number (0-100)
  • isPlugged – will return boolean (true, false)

You can access these events from event listener i.e, document.addEventListener(“eventname”,callbackfunction,false);

Phonegap Battery plugin api example

This is an simple example with phonegap battery api plugin. First Create your phonegap project and add following plugin (battery plugin)

Installation

cordova plugin add org.apache.cordova.battery-status

How it works?

when battery status event occurs, it will call onBatteryStatus function automatically which gives an alert as level and isPlugged Status


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

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

Phonegap Battery plugin api full example


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Battery API</title>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
window.addEventListener("deviceready",init,false);
function init()
{
window.addEventListener("batterycritical",bCritical,false);
window.addEventListener("batterylow",bLow,false);
}
function bCritical(info)
{
alert("Your Battery @ critical Status"+info.level);
}
function bLow(info)
{
alert("Battery @ low"+info.level);
}
function checkbattery()
{
window.addEventListener("batterystatus", onBatteryStatus, false);
}
function onBatteryStatus(info) {
alert("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
</script>
</head>
<body>
<button onclick="checkbattery()">Battery Status</button>
</body>
</html>

Share This

Share this post with your friends!