-3

I registered to receive ACTION_BATTERY_LOW and ACTION_BATTERY_OKAY in an activity and change some behavior according to this.

But I want to know the initial state, when the activity starts. Currently I do it with the following code:

Intent intent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 100);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
boolean batteryLow = 
    (status == BatteryManager.BATTERY_STATUS_DISCHARGING 
           || status == BatteryManager.BATTERY_STATUS_NOT_CHARGING)
    && level * 100 / scale < 15;

This code is both too verbose and maybe different from what android thinks is low. For example, emulator does not report status==discharging, when I issue "power ac off" command to the telnet. I have to issue "power status discharging" as well. Not sure about real device.

Is there any other way?

Oliv
  • 10,221
  • 3
  • 55
  • 76
  • I thought of having global broadcast receiver, that will modify static variable, that I can read anywhere. But the problem remains after application start. – Oliv Jun 04 '14 at 07:03

2 Answers2

-1

Thats as verbose as i can make this

int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

return BatteryManager.BATTERY_STATUS_DISCHARGING && level / (float)scale < 15;
Abs
  • 3,902
  • 1
  • 31
  • 30
-1

As I have found out, the code in the question is the simplest possible one. The warning is shown at 15% battery level, and this value is not available through public API. There is also another level of 10%, when the screen dims. These values are defined during build time, maybe some manufacturers or android versions change it.

See also this answer.

Community
  • 1
  • 1
Oliv
  • 10,221
  • 3
  • 55
  • 76
  • Are you kidding me Oliv? Those are the links from my answer.... is that how YOU found that out? Unbelievable. – Blacklight Jun 04 '14 at 12:36
  • You're right, but your answer is still not correct, I will comment there. I wanted to write a concise and correct answer. – Oliv Jun 04 '14 at 12:38
  • Oh that's right, lets take all the information from others and write your own "correct precise" answer to look better. This is unacceptable behaviour. – Blacklight Jun 04 '14 at 12:42