Search code examples
androidbatterylevelbatterymanager

Android :How to get Battery status without Broadcast Receiver for API level 17 and above?


I want to get Battery status. I searched it on stack and i found the sample code using Broadcast Receiver but problem is that in my code i cannot use Broadcast Receiver.

So is there any way to get battery status without using Broadcast Receiver. It is possible for API 21 and above but i want it for API 17 and above. Thank you


Solution

  • Intent battery=registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    

    battery will contain the last-broadcast ACTION_BATTERY_CHANGED Intent, and its extras will contain the battery information, using the extra keys documented on BatteryManager.

    (this code will work inside a method of a Context subclass; alternatively, call registerReceiver() on some other Context)