Android : how to detect already connected usb device

androidusb

I'm trying to detect usb devices which are already connected to android.
I understand there are actions to detect when USB is either attached or detached.
But I don't really get how to check devices after connecting usb device to android.
Also, I've found that each USB device has it's device class code, but how do I figure out what kind of device is connected? For instance, I need to detect both usb mouse and keyboard; how do I differentiate them?

Best Answer

Try this:

  1. First register Broadcast for USB connection. manifest permission:

:

<intent-filter> <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /> </intent-filter>
  1. Get the List of USB Device with details by using this

    public void getDetail() {
    UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
    
    HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    while (deviceIterator.hasNext()) {
        UsbDevice device = deviceIterator.next();
    
        manager.requestPermission(device, mPermissionIntent);
        String Model = device.getDeviceName();
    
        int DeviceID = device.getDeviceId();
        int Vendor = device.getVendorId();
        int Product = device.getProductId();
        int Class = device.getDeviceClass();
        int Subclass = device.getDeviceSubclass();
    
    }}