I would like to be able to detect whether or not the device is plugged in. I would like to be able to just query that the same way we can do for the connectivity state. Is that possible or do I need to create a broadcast receiver that listens for the battery events?
Asked
Active
Viewed 8,868 times
1 Answers
23
Apparently the ACTION_BATTERY_CHANGED is a "sticky broadcast" which means you can register for it and receive it any time after it has been broadcast. To get the plugged state you can do something like:
public void onCreate() {
BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
if (plugged == BatteryManager.BATTERY_PLUGGED_AC) {
// on AC power
} else if (plugged == BatteryManager.BATTERY_PLUGGED_USB) {
// on USB power
} else if (plugged == 0) {
// on battery power
} else {
// intent didnt include extra info
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(receiver, filter);
}

bensnider
- 3,742
- 1
- 24
- 25
-
That is PERFECT! Thank you! The only thing I thought of was to add `unregisterReceiver(this);` to the `onReceive()` method. – CaseyB Jun 02 '11 at 18:04
-
I've noticed that EXTRA_PLUGGED contains 0 when the device is connected to power but the battery is fully charged. Is there a way to detect that it's still connected to AC so that I can ignore EXTRA_PLUGGED ? – Someone Somewhere Oct 10 '16 at 12:38