Android 获取外部存储设备列表

◇◆丶佛笑我妖孽 提交于 2019-12-05 17:45:45

由于不同芯片设备的外部存储设备不太统一,比如说外部sdcard,u盘等,他们的路径在不同芯片上面的定义是不一样的,所以我们需要动态的去获取机器当前的外部设备mount 的情况

Android 通过 StorageManager 类来管理存储设备的,这个类里面包含一些隐藏的方法:
getVolumeList —–> 返回StorageVolume 类型的数组,包含系统所有的存储设备volume
getVolumePaths—–> 返回String 类型的数组,包含系统所有存储设备的挂在路径

以下以getVolumeList 为例来获取系统所有的可插拔的设备

    priavte StorageManager mStorageManager;
    private Method getStorageVolumes;
    private Method getPath;
    mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
        try {

            getStorageVolumes = mStorageManager.getClass().getMethod("getVolumeList");
            StorageVolume[] volumeList = (StorageVolume[]) getStorageVolumes.invoke(mStorageManager);
            if(volumeList != null){
                for(StorageVolume volume :volumeList){
                    if(volume.isRemovable() && volume.getState().equals("mounted")){
                        getPath = volume.getClass().getMethod("getPath");
                        Log.d("MainActivity", "getPath.invoke(volume.getClass()):" + getPath.invoke(volume));
                        String mountPoint = (String) getPath.invoke(volume);

                    }

                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!