This question already has an answer here:
I've searched on the web and couldn't find the answer to my question. My problem is to get the battery level information only once, eg. calling the function getBatteryLevel()
. There are only solutions which are implemented using BroadcastReceiver
, but as I know it will be called every time on battery level's change event. Please, tell me how can I get that information only once?
The
Intent.ACTION_BATTERY_CHANGED
broadcast is what's known as a "sticky broadcast." Because this is sticky, you can register for the broadcast with a null receiver which will only get the battery level one time when you callregisterReceiver
.A function to get the battery level without receiving updates would look something like this:
More data can be pulled from this sticky broadcast. Using the returned
batteryIntent
you can access other extras as outlined in theBatteryManager
class.