Junsfavorite
Junsfavorite

Reputation: 145

Android : how to detect already connected usb device?

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?

Upvotes: 9

Views: 31303

Answers (2)

Anshuman
Anshuman

Reputation: 328

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

Upvotes: 11

Cristopher Garza
Cristopher Garza

Reputation: 115

Just to answer Benny's question here is what the mPermissionIntent could look like:

string actionString = context.PackageName + ".action.USB_PERMISSION";

PendingIntent mPermissionIntent = PendingIntent.GetBroadcast(context, 0, new 
Intent(actionString), 0);
mUsbManager.RequestPermission(device, permissionIntent);

Upvotes: 8

Related Questions