Stack Overflow archive
14 score

Check if device is plugged in

score
14
question views
47.3K
license
CC BY-SA 3.0

On Android M+ you can use the BatteryManager service via getSystemService(BATTERY_SERVICE). On devices running pre-M you can use a sticky broadcast as mentioned by others. Example:

java
public static boolean isCharging(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        BatteryManager batteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
        return batteryManager.isCharging();
    } else {
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent intent = context.registerReceiver(null, filter);
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        if (status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL) {
            return true;
        }
    }
    return false;
}

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.