![](/img/trans.png)
[英]Android Get OTG USB/External SD CARD Storage devices and their paths
[英]Get all external mounted devices (USB, SD Card)
我已經好幾天都在尋找一個明確的答案,但我仍然不滿意我找到的解決方案。 所以我再次詢問stackoverflow:
有沒有有效的方法可以在Android設備上安裝所有已安裝的外部存儲設備 ? 我知道管理外部存儲總是取決於設備的生產者。 但我不想發布我的應用程序並等待傳入的“錯誤”。
所以我根據兩種不同的設備(三星和宏碁)制作了我的“試錯法”代碼。
附件中的代碼為我的需求提供了最好的結果(但仍然不完美,因為Acer設備的“mnt”和“存儲”中都顯示了SD卡,而且還有更多不同的名稱)。
據我所知,這段代碼不是一種專業的管理方式,請幫助我找到更好的解決方案。
public static List<StorageInfo> getStorageList() {
List<StorageInfo> list = new ArrayList<>();
List<File> typicallFolders = new ArrayList<>();
typicallFolders.add(new File("/storage"));
typicallFolders.add(new File("/mnt"));
int internalNumber = 1;
HashSet<String> knownPaths = new HashSet<>();
for(File fs:typicallFolders) {
try {
if(!fs.exists())
continue;
for (File f : fs.listFiles()) {
File finalPath = getexternalStorage(f, 1);
if (finalPath != null && !knownPaths.contains(finalPath.toString()) && finalPath.canWrite()) {
list.add(new StorageInfo(finalPath.toString(), true, true, internalNumber++));
knownPaths.add(finalPath.toString());
}
}
} catch (Exception e) {
//Catch exception if any
e.printStackTrace();
}
}
return list;
}
private static File getexternalStorage(File path,int depth){
if(Environment.isExternalStorageRemovable(path))
return path;
File[] subFolders = path.listFiles();
if(depth == 3 || subFolders.length != 1){
return null;
}
return getexternalStorage(subFolders[0],depth++);
}
最后,對於我的問題,Jared Rummler的回答完全涵蓋了我的要求。 唯一的問題是我沒有獲得此文件夾的任何權限。 所以我實際做的是使用存儲訪問框架( http://developer.android.com/guide/topics/providers/document-provider.html ),它完全涵蓋了我的需求。 非常感謝Rummler,我真的想把你的答案標記為正確的。 請提供您的推薦作為答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.