Battery status is not always charging

@Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
    BatteryManager.BATTERY_STATUS_UNKNOWN);

    if (status == BatteryManager.BATTERY_STATUS_CHARGING
        || status == BatteryManager.BATTERY_STATUS_FULL)
        Toast.makeText(context, "Charging!", Toast.LENGTH_SHORT).show();
    else
        Toast.makeText(context, "Not Charging!", Toast.LENGTH_SHORT).show();
}

manifest:

<receiver android:name=".receiver.BatteryReceiver">
    <intent-filter>
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
        <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
        <action android:name="android.intent.action.BATTERY_CHANGED" />
    </intent-filter>
</receiver>

In this code, Toast always shows "Not Charging!" I tested this on a real device, and when I plug it into AC or USB, it still displays "Not Charging!" Toast.

+5
source share
2 answers

You cannot register on ACTION_BATTERY_CHANGEDthe manifest so that you do not receive these broadcasts. You are trying to get BatteryManageradditional functions from Intentsthat do not have these additional functions (for example, ACTION_POWER_CONNECTED). As a result, you get the default value BATTERY_STATUS_UNKNOWN.

+6
source

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 have a value from 1 to 5:

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

:

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

:

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

, BatteryManager.BATTERY_STATUS_CHARGING - , 2, BatteryManager.BATTERY_STATUS_FULL - , 5.

+2

All Articles