-2

I am trying to sample accurate battery levels in my application but I'm really struggling. Currently I have:

String s = String.valueOf(BATTERY_PROPERTY_CURRENT_NOW);
batteryShow.setText(s);

but just returns 2 on different devices and different powers. Ideally I would get the vale in mAh but any suggestions would go along way.

NOTE I have looked at

https://developer.android.com/training/monitoring-device-state/battery-monitoring.html

without much joy.

takendarkk
  • 3,347
  • 8
  • 25
  • 37
  • you need to use broadcast receiver , so that you can receive battery levels – iamkdblue Mar 02 '18 at 17:45
  • Unrelated: `BATTERY_PROPERTY_CURRENT_NOW` is a constant, a key to get the real value. How did you manage to arrive to `String.valueOf` based on that article? – Eugen Pechanec Mar 02 '18 at 17:47

1 Answers1

1

BATTERY_PROPERTY_CURRENT_NOW is a constant, a key that helps you get the real value.

final BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
final int current = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);

Read more:

Community
  • 1
  • 1
Eugen Pechanec
  • 37,669
  • 7
  • 103
  • 124
  • this gives -397 on a Samsung s7 with 32% so not sure where to go from there –  Mar 02 '18 at 18:03
  • 2
    -397 means the current *discharging* from battery is 397 mA, as mentioned in the linked documentation. Some values are exposed as properties. Some values are exposed via a sticky intent, [your link](https://developer.android.com/training/monitoring-device-state/battery-monitoring.html#DetermineChargeState) perfectly describes it already. **At least try to read the damn documentation and look for the property you're looking for.** Is it [`BATTERY_PROPERTY_CAPACITY`](https://developer.android.com/reference/android/os/BatteryManager.html#BATTERY_PROPERTY_CAPACITY)? – Eugen Pechanec Mar 02 '18 at 18:28
  • No I think it's BATTERY_PROPERTY_CHARGE_COUNTER, sorry I am new to this. I have tried putting the new property into the code but only get a value of 0.I am wondering if my samsung is not one of the devices to support this? –  Mar 03 '18 at 12:00
  • "Battery capacity in microampere-hours, as an integer." That's micro amper hours. Multiply it by 1000 to get milli amper hours. Anyway if it's zero, it looks unsupported. Search "android samsung battery capacity programmatically" or equivalent, perhaps there's another method. Avoid generic terms such as "levels", look how long it took us to get here. – Eugen Pechanec Mar 03 '18 at 12:10
  • I've run it on a nexus 6 which supports it and still getting 0 so there must be something incorrect with the code. I have searched that, many times, and no one seems to be getting a solution which is why I decided to ask my own question. –  Mar 03 '18 at 12:17