How to list files on a USB OTG device

I know how to do this:

  • listen to attaching and disconnecting events of USB devices
  • retrieve all connected devices
  • obtaining device permissions

So, I have a UsbDevice , and I have read / write permissions. How to continue here?

I can open the device and get a FileDescriptor as shown below:

  UsbManager manager = (UsbManager) activity.getSystemService(Context.USB_SERVICE); UsbInterface intf = device.getInterface(0); UsbEndpoint endpoint = intf.getEndpoint(0); UsbDeviceConnection connection = manager.openDevice(device); boolean interfaceClaimed = connection.claimInterface(intf, true); int fileDescriptor = connection.getFileDescriptor(); 

How can I work with this FileDescriptor now? Or how else can I access files on a USB device?

EDIT

  • Solution for android <6: Do not open the UsbDeviceConnection and just try to find the path of the USB devices. However, you have a problem distinguishing between multiple USB devices and don’t know which path belongs to the device ...

  • Solution for android> = 6: use the Storage Access Framework, in fact I don’t know how this works yet ...

+5
source share
1 answer

Since I'm as dumb as you are, I would go the way of using the ls .

Code example:

 try { Process process = Runtime.getRuntime().exec("ls /storage/UsbDriveA"); BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); String listOfFiles = ""; String line; while ((line = buffer.readLine()) != null) { listOfFiles += line; } } catch (InterruptedException e) { e.printStackTrace(); } 

ls will return no such file or directory if the mount point is incorrect.

Here is a list of many mount point manufacturers:

 /storage/UsbDriveA (all Samsung devices) /storage/USBstorage1 (LG G4, V10, G3, G2, other LG devices) /storage/usbdisk (Moto Maxx, Turbo 2, Moto X Pure, other Motorola devices) /storage/usbotg (Sony Xperia devices, Lenovo Tabs) /storage/UDiskA (Oppo devices) /storage/usb-storage (Acer Iconia Tabs) /storage/usbcard (Dell Venue -- Vanilla Android 4.3 tablet) /storage/usb (HTC One M7, and some Vanilla Android devices) 

(Based on my collection of devices and 3 other people and a quick trip to Bestbuy for testing the latest flagships. The only popular devices that I know I miss are Hawuei / Xioami devices based in China, which are becoming popular in English countries, but they probably use one of the above.)

To find the mount point you need, you must listen to no such file or directory and loop / re-execute the exec() statement with the next mount point.

Once all this is done, you can easily read the files using cat /storage/.../file.txt and write using redirection: echo test > /storage/.../file.txt

Hope this helps

+3
source

Source: https://habr.com/ru/post/1241832/


All Articles