As an android developer, I want to retrieve serialNumber of USB Device which can be flash drive, mouse, keyboard which is just connected to an Android TV.
I read one can use getSerialNumber() method of UsbDevice class to retrieve this non-resettable identifier. But how to get the UsbDevice object corresponding to the device which is just connected.
I tried fetching the same using USB_DEVICE_ATTACHED android intent but found out the intent broadcasted is not being received by the system app. Same problem is listed here as well.
Also, is there an way to retrieve the same without depending on the intent ?
- For example, to get the recently connected storage volume, one can use the getStorageVolumes() method which return an list. And then one can iterate over the list & get the first volume which is removable & this would be the flash drive which is recently connected.
public static String getPendriveDeviceId(Context context) {
StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
if (storageManager != null) {
StorageVolume[] storageVolumes = storageManager.getStorageVolumes();
for (StorageVolume storageVolume : storageVolumes) {
// Check if the storage volume is a removable USB drive
if (storageVolume.isRemovable()) {
// Get the unique ID associated with the storage volume
String deviceId = storageVolume.getUuid();
return deviceId;
}
}
}
// Return null if no pendrive is found
return null;
}
- But same logic doesn't work to fetch the UsbDevice object as UsbManager.getDeviceList() returns an HashMap instead of an list
I finally find out what I was missing in the code due to which
USB_DEVICE_ATTACHEDintent was not being received. So, I added ameta-datafield inside the receiver with thedevice_filter.xmlfile. And now with this change everything is working as expected.And the device_filter.xml file is :
Since, I wanted the logic to work for all usb device irrespective of the vendor & product id, I wrote
device_filter.xmlfile in this way