check USB attached or not in a button click android

274 views Asked by At

In a button click, I want to check any USB is connected to the device or not. If connected then some action(may be a toast).When a button is clicked a broadcast for checking if USB is connected or not.

1

There are 1 answers

1
Ilya Gazman On

I am not sure about all the censorious but here how you test if your device is charging:

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;
    }
}

Found at this question.

Edit: Using UsbManager.getDeviceList you get all the connected devices. So if size is 0 no USB is connected.