6
@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.

Mohit Deshpande
  • 53,877
  • 76
  • 193
  • 251

2 Answers2

6

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • So how would I register it programmatically? – Mohit Deshpande Jul 22 '12 at 18:33
  • 1
    @MohitDeshpande: Call `registerReceiver()`, the same way you would register any other `BroadcastReceiver` programmatically. See: https://github.com/commonsguy/cw-omnibus/tree/master/SystemEvents/OnBattery – CommonsWare Jul 22 '12 at 18:35
3

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.

VikingGlen
  • 1,705
  • 18
  • 18
  • 1
    Good answer, but please do not use magic numbers in code: http://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad – kellogs Jan 20 '17 at 13:13