Battery status is always not charging

放肆的年华 提交于 2019-12-01 17:01:05

You cannot register for ACTION_BATTERY_CHANGED via the manifest, so you are not receiving those broadcasts. You are trying to get BatteryManager extras from Intents that do not have those extras (e.g., ACTION_POWER_CONNECTED). As a result, you are getting the default value of BATTERY_STATUS_UNKNOWN.

Try the following:

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

'status' will now be a value between 1 and 5:

1 = Unknown
2 = Charging
3 = Discharging
4 = Not Charging
5 = Full

Your code:

if (status == BatteryManager.BATTERY_STATUS_CHARGING
    || status == BatteryManager.BATTERY_STATUS_FULL) ...

can be written:

if (status == 2 || status == 5) ...

Both are identical because BatteryManager.BATTERY_STATUS_CHARGING is a constant that always equals 2, and BatteryManager.BATTERY_STATUS_FULL is a constant that always equals 5.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!