![](/img/trans.png)
[英]Access and manipulate files and directories on an external USB storage in a rooted Android device
[英]Get access to USB mass storage device in android
所以我有一根插在手機上的小電纜,另一邊有一個USB端口,你可以插入一個閃存盤,如你所見:
當我插入閃存驅動器時,我收到一條通知說:
USB大容量存儲連接
當我啟動文件資源管理器應用程序時,我可以看到驅動器位於:
/存儲/ 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);
}
}
}
在我的清單中,我有這些線,雖然我不確定它們都是強制性的......
<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" />
我無法測試這個,我自己沒有這樣的電纜,但我的假設是你可以將你的文件路徑直接傳遞給構造函數,如下所示:
File directory = new File("/storage/UsbDriveA/");
你試過這個嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.