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 ?
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;
}
I finally find out what I was missing in the code due to which USB_DEVICE_ATTACHED
intent was not being received. So, I added a meta-data
field inside the receiver with the device_filter.xml
file. And now with this change everything is working as expected.
<receiver
android:name=".receiver.MediaMountedBroadcastReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/device_filter" />
</receiver>
And the device_filter.xml file is :
<?xml version="1.0" encoding="utf-8"?>
<resources>
<usb-device/>
</resources>
Since, I wanted the logic to work for all usb device irrespective of the vendor & product id, I wrote device_filter.xml
file in this way