- 添加USB设备权限到AndroidManifest.xml文件中。
- 使用UsbManager获取USB设备信息。
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap deviceList = usbManager.getDeviceList();
- 使用UsbDeviceConnection打开对应的USB设备。
UsbDevice usbDevice = deviceList.get(deviceName);
UsbDeviceConnection connection = usbManager.openDevice(usbDevice);
- 获取USB设备中的文件列表。
File root = new File("/mnt/usb_storage/USB_DISK0/");
File[] fileList = root.listFiles();
- 使用RecyclerView或ListView显示USB设备中的文件列表。
完整代码如下:
private void showUsbDeviceContents() {
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap deviceList = usbManager.getDeviceList();
String deviceName = getIntent().getStringExtra("deviceName");
if (deviceName == null) {
return;
}
UsbDevice usbDevice = deviceList.get(deviceName);
if (usbDevice == null) {
return;
}
UsbDeviceConnection connection = usbManager.openDevice(usbDevice);
if (connection == null) {
return;
}
connection.claimInterface(usbInterface, true);
File root = new File("/mnt/usb_storage/USB_DISK0/");
File[] fileList = root.listFiles();
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new FileAdapter(fileList));
}