Search code examples
javaandroidstatuspower-management

Battery status is always not 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, the Toast always shows "Not Charging!". I tested this on an actual device, and when I plug it into AC or USB power, it still displays the "Not Charging!" Toast.


Solution

  • 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.