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?
Asked
Active
Viewed 2.7k times
2 Answers
9
Try this:
- First register Broadcast for USB connection. manifest permission:
:
<intent-filter> <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /> </intent-filter>
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(); }}

Tony Barajas
- 124
- 2
- 12

Anshuman
- 308
- 2
- 6
-
The device class and subclass should tell you information about the device, unless it is vendor specific - in which case you should be able to look at the VID/PID - but you'd have to know what vendor specific device you're looking for. – Preston May 13 '15 at 02:48
-
6What is the `mPermissionIntent` ?? how can i create this ? – Benny Dec 21 '16 at 11:48
6
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);

Cristopher Garza
- 95
- 1
- 7
-
1`string actionString = context.PackageName + ".action.USB_PERMISSION";` is wrong. It should be `string actionString = context.PackageName + ".USB_PERMISSION";` – AkshayT May 31 '17 at 04:36