1

I'm aware that I can register a BroadcastReceiver for ACTION_BATTERY_LOW and ACTION_BATTERY_OKAY which will notify my app when this battery LOW state changes, but how can I determine if the battery is currently LOW or OKAY?

BatteryManager may allow me to get the current percentage and status, but it doesn't appear to expose a status for LOW.

HolySamosa
  • 9,011
  • 14
  • 69
  • 102

2 Answers2

1

The ACTION_BATTERY_CHANGED broadcast is a sticky broadcast. And one of the extras is ACTION_BATTERY_LOW.

So this little method should do what you need

private boolean isBattteryLow() {
    IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryIntent = context.registerReceiver(null, filter);
    return batteryIntent.getBooleanExtra(BatteryManager.EXTRA_BATTERY_LOW, false);
}
0

If you want to know at what percentage the system is sending you the LOW status it would probably be best to register the ACTION_BATTERY_LOW broadcast receiver in the manifest and calculate the percentage from BatteryManager when you get the LOW event, save it and use it later to determine LOW status based on the data you can get from BatteryManager.

Since the LOW broadcast is not sticky I guess it is the only way.

I think most of the devices send LOW event at 15%, so it would be a good starting point.

TpoM6oH
  • 8,385
  • 3
  • 40
  • 72
  • Thanks! This occurred to me, but I was hoping for a better way as this would require me to either get the battery warning level configured for the device (which `BatteryService` does when deciding to broadcast the LOW / OKAY actions) or as you suggest, make up my own threshold which may not agree with the system. It's rather annoying that LOW / OKAY seemingly can't be queried... – HolySamosa Jun 28 '17 at 21:27