怎么在Android中获得所有存储设备位置?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
具体代码如下:
public static List<HomeDirBean> getAllExternalStorage(Context context) {
List<HomeDirBean> storagePath = new ArrayList<>();
StorageManager storageManager = (StorageManager) context.getSystemService(STORAGE_SERVICE);
StorageVolume[] storageVolumes;
try {
Method getVolumeList = StorageManager.class.getDeclaredMethod("getVolumeList");
storageVolumes = (StorageVolume[]) getVolumeList.invoke(storageManager);
Method getVolumeState = StorageManager.class.getDeclaredMethod("getVolumeState", String.class);
for (StorageVolume storageVolume : storageVolumes) {
String desc = storageVolume.getDescription(context);
Log.i(TAG, "storageVolume name--->" + desc);
Method getPath = StorageVolume.class.getMethod("getPath");
String path = (String) getPath.invoke(storageVolume);
Log.i(TAG, "StoragePath--->" + path);
//这里需要用StorageManager反射调用getVolumeState函数,而不应该用StorageVolume的getState方法,因为可能会报错
String state = (String) getVolumeState.invoke(storageManager, path);
Log.i(TAG, "storageVolume State--->" + state);
if (Environment.MEDIA_MOUNTED.equals(state)) {
HomeDirBean bean = new HomeDirBean(path, desc);
storagePath.add(bean);
}
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return storagePath;
}
这里需要注意,可能有小伙伴会问,既然StorageVolume类有getState方法,为啥还要用StorageManager反射调用getVolumeState方法,并传入path地址,而在源码里,StorageManager的getVolumeState的方法的实现,也是将path重新创建为StorageVolume类,然后再调用其getState方法,我们这样做成这不是多此一举吗?
源码截图如下:
Android是一种基于Linux内核的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由美国Google公司和开放手机联盟领导及开发。
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。