Android 无法解析符号:Context.BATTERY_SERVICE

Android cannot resolve symbol: Context.BATTERY_SERVICE

对于应用程序,我需要以微安为单位监控平均电池电流。我像这里描述的那样做了: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;
}

但是我得到了 "Cannot resolve symbol BATTERY_SERVICE"。

上下文是对 Activity 的引用。

我做错了什么?

BATTERY_SERVICE 已添加到 API 级别 21。将您的 compileSdkVersion 设置为 21,并确保您仅在 API 级别 21+ 设备上执行此代码.