Android获取设备挂载的U盘路径的方法有哪些?给出java代码,Android8.0以上
时间: 2024-06-11 18:05:09 浏览: 212
Android编程实现识别与挂载U盘的方法
1. 使用StorageManager获取U盘路径
```java
StorageManager storageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
List<StorageVolume> storageVolumes = storageManager.getStorageVolumes();
for (StorageVolume volume : storageVolumes) {
if (volume.isRemovable() && volume.getState().equals(Environment.MEDIA_MOUNTED)) {
File file = volume.getDirectory();
String path = file.getAbsolutePath();
Log.d(TAG, "U盘路径:" + path);
}
}
```
2. 使用StorageStatsManager获取U盘路径
```java
StorageStatsManager storageStatsManager = (StorageStatsManager) getSystemService(Context.STORAGE_STATS_SERVICE);
StorageManager storageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
List<StorageVolume> storageVolumes = storageManager.getStorageVolumes();
for (StorageVolume volume : storageVolumes) {
if (volume.isRemovable() && volume.getState().equals(Environment.MEDIA_MOUNTED)) {
File file = volume.getDirectory();
try {
StorageStats storageStats = storageStatsManager.queryStatsForUuid(volume.getUuid());
long totalSize = storageStats.getTotalBytes();
long availableSize = storageStats.getAvailableBytes();
String path = file.getAbsolutePath();
Log.d(TAG, "U盘路径:" + path);
Log.d(TAG, "总大小:" + totalSize);
Log.d(TAG, "可用大小:" + availableSize);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意:在Android 11及以上版本中,由于数据访问权限的限制,使用以上方法获取到的U盘路径可能为空。可以通过使用`ACTION_OPEN_DOCUMENT_TREE`打开系统文件浏览器,让用户手动选择U盘路径的方式来解决。
阅读全文