可以访问USB大容量存储设备的android大容量、存储设备、USB、android

2023-09-05 08:32:00 作者:我们没未来

所以我有这个,你插入到你的手机的小电缆,电缆的另一端,您可以在例如闪存驱动器插入USB端口,你可以在这里看到:

So I have this little cable that you plug into your phone that has a USB port on the other side where you can plug in a flash drive for example, as you can see here:

当我插入闪存驱动器,我收到了通知,上面写着:

When I plug in a flash drive I get a notification that says:

USB大容量存储连接

USB mass storage connected

当我再推出一个文件浏览器应用程序,我可以看到,该驱动器则位于:

When I then launch a file explorer app I can see that the drive is then located at:

/存储/ UsbDriveA /

/storage/UsbDriveA/

和这是伟大的,但我想知道如何获得我的code使用闪存驱动器。 SD卡获取的访问是很容易的:

And that's great, but I want to know how to gain access to the flash drive in my code. Getting access to the SD card is easy enough:

File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/MyFiles")
directory.mkdirs();

但你会如何在闪存驱动器的情况下做到这一点?提前致谢! :)

But how would you do this in the case of the flash drive? Thanks in advance! :)

推荐答案

在这个例子中,我使用Apache的文件实用程序,但是没有它时,你会看到用来读取USB闪存驱动器的逻辑:

In this example I am using the FileUtils from Apache, but event without it you will see the logic used to read a USB Flash drive:

private UsbManager usbManager;
private UsbDevice clef;
ArrayList<File> images;

usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
clef = null;

if (usbManager != null)
{
    HashMap<String,UsbDevice> deviceList = usbManager.getDeviceList();
    if (deviceList != null)
    {
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while (deviceIterator.hasNext()) {
            clef = deviceIterator.next();
        }
    }
}

if (clef != null)
{
    File directory  = new File("/storage/UsbDriveA/");
    if (directory != null) {
        if (directory.canRead()) {

            images = new ArrayList<File>();
            String[] imageExtensions = {"jpg","jpeg","png","gif","JPG","JPEG","PNG","GIF"};
            Iterator<File> iterateImages = FileUtils.iterateFiles(directory, imageExtensions, true);
            while (iterateImages.hasNext()) {
                File theImage = iterateImages.next();
                if (!theImage.getName().startsWith(".", 0))
                    images.add(theImage);
            }

            // custom process / methods... not very relevant here : 
            imageIndex = 0;
            scale = 1.0f;
            countImgs = images.size();
            loadImage(imageIndex);
        }
    }
}

在我的表现我的线,但我不知道他们都是强制性的......

In my manifest I have those lines, although I'm not sure they're all mandatory...

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.USB_PERMISSION" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />