作为一名 Android 开发人员,我想检索 USB 设备的序列号,该设备可以是刚刚连接到 Android TV 的闪存驱动器、鼠标、键盘。
我读到可以使用 getSerialNumber() 方法 UsbDevice 类来检索此不可重置标识符。但是如何获取刚刚连接的设备对应的UsbDevice对象。
我尝试使用
USB_DEVICE_ATTACHED
android 意图获取相同的内容,但发现系统应用程序没有收到广播的意图。同样的问题也在这里列出。
还有,有没有一种方法可以在不依赖意图的情况下检索相同的内容?
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;
}
虽然系统应用程序可能无法接收 USB_DEVICE_ATTACHED 意图,但仍有其他方法可以实现您的目标。
您可以考虑的一种方法是使用 UsbManager 的 getDeviceList() 方法来获取所有已连接 USB 设备的映射。从那里,您可以遍历地图并检查您是否感兴趣每个设备,例如闪存驱动器、鼠标或键盘。这是一个例子:
public static UsbDevice getRecentlyConnectedDevice(Context context) {
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
if (usbManager != null) {
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
for (UsbDevice device : deviceList.values()) {
// Check if the device is a flash drive, mouse, or keyboard
if (device.getDeviceClass() == UsbConstants.USB_CLASS_MASS_STORAGE ||
device.getDeviceClass() == UsbConstants.USB_CLASS_HID) {
return device;
}
}
}
// Return null if no matching device is found
return null;
}
通过这种方式,可以获得最近连接的USB设备对应的UsbDevice对象。从那里,您可以使用前面提到的 getSerialNumber() 方法检索序列号。
请记住在访问 UsbDevice 对象之前处理必要的 USB 权限,例如在需要时向用户请求权限。