在Android中访问USB大容量存储设备

因此,我将这根小电缆插入您的手机,该手机的另一侧具有USB端口,例如,您可以在其中插入闪存驱动器

当我插入闪存驱动器时,我收到一条通知,内容为:

已连接USB大容量存储

然后,当我启动文件浏览器应用程序时,我可以看到驱动器

位于:

/ storage / UsbDriveA /

太好了,但是我想知道如何在

代码中访问闪存驱动器。轻松访问SD卡:

File sdCard = Environment.getExternalStorageDirectory();

File directory = new File (sdCard.getAbsolutePath() + "/MyFiles")

directory.mkdirs();

但是,对于闪存驱动器,您将如何做呢?提前致谢!

回答:

在此示例中,我使用的是来自Apache的FileUtils,但是如果不使用它,您将看到用于读取USB闪存驱动器的逻辑:

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" />

以上是 在Android中访问USB大容量存储设备 的全部内容, 来源链接: utcz.com/qa/414536.html

回到顶部