Android 如何列出USB OTG设备上的文件

Android 如何列出USB OTG设备上的文件,android,usb,usb-otg,Android,Usb,Usb Otg,我知道如何做到以下几点: UsbManager manager = (UsbManager) activity.getSystemService(Context.USB_SERVICE); UsbInterface intf = device.getInterface(0); UsbEndpoint endpoint = intf.getEndpoint(0); UsbDeviceConnection connection = manager.openDevice(device); b

我知道如何做到以下几点:

 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();
  • 侦听usb设备的附加和分离事件
  • 获取所有连接的设备
  • 正在获取设备的权限
所以最后我有了一个
UsbDevice
,我有读/写它的权限。从这里怎么走

我可以打开设备并获得一个
文件描述符
,如下所示:

 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();
现在如何使用此
FileDescriptor
?或者如何访问USB设备上的文件

编辑

  • 安卓<6的解决方案:不要打开
    UsbDeviceConnection
    ,只需尝试查找usb设备路径即可。不过,你还是有问题区分多个usb设备,不知道哪个路径属于哪个设备

  • android的解决方案>=6:使用存储访问框架,实际上我还不知道它是如何工作的


    • 因为我和你一样难堪,所以我会选择使用
      ls
      命令

      代码示例:

      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
      将返回
      无此类文件或目录

      以下是制造商使用的许多安装点的列表:

      /storage/UsbDriveA(所有三星设备)
      /存储/USB存储1(LG G4、V10、G3、G2、其他LG设备)
      /存储/usbdisk(Moto Maxx、Turbo 2、Moto X Pure、其他摩托罗拉设备)
      /存储/usbotg(索尼Xperia设备、联想标签)
      /存储/UDiskA(Oppo设备)
      /存储/usb存储(Acer Iconia标签)
      /存储/usbcard(戴尔会场——香草安卓4.3平板电脑)
      /存储/usb(HTC One M7和一些普通安卓设备)
      
      (根据我收集的设备和其他3个人的,以及去百思买测试最新旗舰的快速旅行。我知道我缺少的唯一流行设备是中国的Hawuei/Xioami设备,这些设备在英国国家越来越流行,但它们可能使用上述其中一种。)

      要找到正确的装入点,您需要侦听
      没有这样的文件或目录
      ,然后循环/重新执行
      exec()
      语句和下一个装入点

      完成所有这些操作后,您可以使用
      cat/storage/../file.txt轻松读取文件,并使用重定向进行写入:
      echo test>/storage/../file.txt


      希望这能有所帮助

      大多数情况下,棒会安装在文件系统文件夹中,如/storage/usbdrive等。在Marshmellow下,路径不存在,您可以使用存储访问框架。实际上你知道如何区分usb设备吗?我可以找到usb存储器的所有可用路径,但我不知道哪个路径属于哪个设备。我从来没有看到过不止一条usb驱动器路径。你在哪里可以看到更多?通过usb otg,你可以安装任何东西,usb驱动笔,外部硬盘,甚至是一个最终有很多卡的外部读卡器…是的。当有很多卡片时,你看到了什么路径?哪个设备显示了这个?