Android: Detecting USB

Some people suggested using UMS_CONNECTED which is deprecated as of recent version of Android
The other problem with that is that it does not work with MTP enabled devices

Others suggested the use of the BatteryManager, more precisely ACTION_BATTERY_CHANGED as well as BATTERY_PLUGGED_AC and BATTERY_PLUGGED_USB
This is perfect if you want to detect the Battery or Charging status of the device, but is not a really good indicator of a USB connection.
Using the battery manager is prone to failure on older android tablets such as the XOOM, the ICONIA tab A510, and the older Asus tablets.

To purely detect that the device was plugged on a PC you can:
Use android.hardware.usb.action.USB_STATE and connected
in place of the BatteryManager stuff

Code sample

public static boolean isConnected(Context context) {
        intent = context.registerReceiver(null, new IntentFilter("android.hardware.usb.action.USB_STATE"));
        return intent.getExtras().getBoolean("connected");
    }

Hope this helps

Leave a Comment