8

Function like

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

function onBatteryStatus(info)
{
 // Handle the online event
    console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}

return battery level and status when event is fired. In normal case, how can I get status of battery run time without writing plugin.

Also if is there any API or other related/alternate solution, please mention.

Kamesh Jungi
  • 6,203
  • 6
  • 39
  • 50
  • you HAVE to use this plugin, https://github.com/apache/cordova-plugin-battery-status, you cannot access battery status and level without using cordova plugin – Nadeem Khoury Dec 18 '15 at 10:31
  • @Kamesh: I have the same problem now. Did you found a solution to get the current battery status? – Iker Vázquez Jul 01 '16 at 16:30
  • @NadeemKhoury: This plugin appears to only be registering events for when the battery status changes, not returning the status directly. Do you know if this fires the appropriate events on initialization, or is it possible that you will never get the status if it never changes somehow? How do you get the status for immediate use instead of having to wait for an event to tell you? – Trevortni Dec 06 '16 at 01:00
  • @Trevortni look at my answer bro. tell me if it works or not ? – Nadeem Khoury Dec 06 '16 at 14:47
  • @NadeemKhoury: That actually doesn't address my question at all, or supply any new information not already included at the link you gave before, unless the answer is that no, it doesn't do what has been asked, in which case it would have been much simpler to just say that. – Trevortni Dec 07 '16 at 01:22
  • @Trevortni this method returns immediate status, I have tried and it worked. please try it – Nadeem Khoury Dec 07 '16 at 11:44
  • I have the same problem like Treveortni. How can I check the current battery status if it is plugged in or not WITHOUT changing the plug? – desmeit Oct 17 '17 at 15:18

2 Answers2

0

@Trevortini, Please check this link: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-battery-status/

batterystatus event

Fires when the battery charge percentage changes by at least 1 percent, or when the device is plugged in or unplugged. Returns an object containing battery status.

Example:

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

function onBatteryStatus(status) {
    console.log("Level: " + status.level + " isPlugged: " + status.isPlugged);
}

Cheers.

Nadeem Khoury
  • 886
  • 6
  • 18
  • 2
    this is only showing the status on change, not directly with the first call. Do you have a solution without changing? – desmeit Oct 17 '17 at 17:49
0

Don't use the event, just use battery.level (Phonegap Build 8.1.1 with latest plugin phonegap-plugin-battery-status)

if( typeof navigator.getBattery!='undefined' ){

    navigator.getBattery().then(function(battery) {

        alert('Battery Level: '+battery.level);

    });

}
else{
    alert('Plugin missing');
}