One of the interesting things added in PhoneGap 1.3.0 (and something I missed until fairly recently), was support for battery events. Using these events is pretty simple so I thought I’d whip up a quick demo.
Before going any further, note that there is currently a documentation bug. While the API as described works perfectly, you will not be able to use these events unless you do two things:
1) Edit your plugins.xml file to include this: <plugin name="Battery" value="com.phonegap.BatteryListener"/>. You normally only edit this file when adding additional plugins. I'm betting that the PhoneGap devs forgot to update the default plugins.xml file.
2) The second thing you need to do I was able to skip as my project already had it. You must ensure the BROADCAST_STICKY permission is enabled in AndroidManifest.xml. Again, for my project this was already done.
There are three main events you can listen to:
- batterystatus: Fired when the battery level changes or if the device is plugged in/removed.
- batterylow: Fired when the battery is low. The definition of "low" is device dependent.
- batterycritical: Ditto the above.
Note that there is no generic way to get the status of the battery right now. In my testing, batterystatus seemed to fire immediately. So it's probably safe to use it to get your status on application startup, but keep in mind it may not be immediate for you.
All three events pass a simple object containing two keys: level and isPlugged. level is a numeric percentage value. isPlugged is a boolean representing if the device is plugged in or not.
Here's a simple demo:
As you can see, I've got listeners for all three events, with the low and critical going out of their way to warn the user that bad times are ahead. Here's a quick screen shot to give you an idea of how it renders.
So obviously you wouldn't typically need to show the battery status at all times. I could definitely see using the low/critical events to warn the user to save their work or perform some other safekeeping measures in case the device suddenly shuts down.
p.s. I can't post this blog entry without a quick shoutout to one of my coworker's recent PhoneGap demo. Batteries are boring. Multiple screens are freaking cool: Multi-Screen iOS Apps with PhoneGap