Search code examples
androidusbbroadcastreceiverwireless

android USB connection charging signals


How can I check the USB socket is plugged or not (Charging with AC / USB)? (android version 2.1 / 2.2)

I am writing a wireless charging application that I want to get different types of charging signals ( wireless , AC charging / USB ). I used broadcastReceiver to get the charging signal and found that using wireless charging and AC charging return the same signal (AC charging). To distinguish wireless charging and AC charging, I want to detect the USB socket is plugged or not. I try to use Intent.ACTION_UMS_CONNECTED to detect the USB signal but it also return SD card.

How can I check the USB socket is plugged or not (Charging with AC / USB)? (android version 2.1 / 2.2)


Solution

  • To check device charging with AC / USB, Lets try this,

    Call registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)). This will return an Intent that has extras defined on BatteryManager to let you know if it is plugged in or not.

    Something with code,

    public class PowerUtil {
        public static boolean isConnected(Context context) {
            Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
            return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
        }
    }