Search code examples
androidbatterymanager

Android cannot resolve symbol: Context.BATTERY_SERVICE


for an App I need to monitor the Average battery current in micro amperes. I did it like described here: https://source.android.com/devices/tech/power/index.html#device-power

private long getPowerConsumption() {
    BatteryManager mBatteryManager;
    mBatteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
    long energy = mBatteryManager.getLongProperty(BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER);
    return energy;
}

But I'm getting a "Cannot resolve symbol BATTERY_SERVICE".

The context is a reference to an Activity.

What I'm doing wrong?


Solution

  • BATTERY_SERVICE was added in API Level 21. Set your compileSdkVersion to 21, and ensure that you only go through this code on API Level 21+ devices.