Battery is expensive. Not to say that you can’t buy one, but you really should use resources wisely when you develop a mobile application. Yet sometimes you need to do some long run process or heavy calculation.
For that matter, Android allows us to detect whether the device is plugged in and charging. Let’s see how.
One thing we can do is ask whether the device is plugged-in. That can easily be done with a few lines of code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Note that charge efficiency may change according to the type of power source. You may want to investigate the
BatteryManager.EXTRA_PLUGGED to get more information.
Astute readers will notice that we used a sticky broadcast to get the status. It means we can also create a BroadcastReceiver to monitor changes for the battery status. This is left as an exercise to you, dear reader :)
You can checkout the example on github.