首先,通过调用 getSystemService(StorageManager.class)
方法获取系统的 StorageManager
对象。然后调用 storageManager.getStorageVolumes()
方法获取所有的存储卷。
StorageManager storageManager =getContext().getSystemService(StorageManager.class);
List<StorageVolume> volumes = storageManager.getStorageVolumes();
接着,通过遍历存储卷列表,针对每个存储卷调用 getPathFile()
方法获取其对应的路径 path
。volume.isPrimary()用于判断是否为主存储卷。
最后,返回一个包含 USB 存储设备路径的空 HashMap 对象 paths
。需要注意的是,在这段代码中并没有给 paths
对象添加键值对,因此返回的 paths
对象始终为空。如果需要将 USB 存储设备路径存储到 paths
中,可以在 else
分支中添加以下代码:
paths.put(volume.getDescription(getContext()), path.getAbsolutePath());
这样,就可以将 USB 存储设备的描述和绝对路径存储到 paths
对象中了。
以下是完整的代码部分:
public HashMap<String, String> getUsbDrivePath() {
StorageManager storageManager = getContext().getSystemService(StorageManager.class);
List<StorageVolume> volumes = storageManager.getStorageVolumes();
HashMap<String, String> paths = new HashMap<>();
volumes.forEach(new Consumer<StorageVolume>() {
@Override
public void accept(StorageVolume volume) {
File path = getPathFile(volume);
Log.d(TAG, "accept: " + path);
if (volume.isPrimary()) {
//不是USB设备
//TODO
}else{
//是USB设备,添加自己的逻辑
//TODO
}
}
});
return paths;
}