Android6.0以上系统获取内置SD和外置SD卡路径的方法

发布时间:2024-01-08 04:22:17

以前写了一篇文章也是说获取内外SD卡路径的:Android获取手机自带SDCard和外置SDCard路径,但是只适用于5.0及以下的系统。

在Android Studio中使用,StorageVolume是在Android7.0(api24)里面才添加的类

/**
     * 获取SD卡路径
     * @param mContext
     * @param is_removable SD卡是否可移除,不可移除的是内置SD卡,可移除的是外置SD卡
     * @return
     */
    public static String getStoragePath(Context mContext, boolean is_removable) {

        StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
        Class<?> storageVolumeClazz = null;

        try {
            storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
            Method getState = storageVolumeClazz.getMethod("getState");
            Object result = getVolumeList.invoke(mStorageManager);
            final int length = Array.getLength(result);
            for (int i = 0; i < length; i++) {
                Object storageVolumeElement = Array.get(result, i);
                String path = (String) getPath.invoke(storageVolumeElement);
                String state = (String) getState.invoke(storageVolumeElement);

                boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);

                if (is_removable == removable) {
                    return path;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

参考文章:http://blog.csdn.net/u010838555/article/details/51783384

转载于:https://my.oschina.net/yuewawa/blog/1540540

文章来源:https://blog.csdn.net/weixin_34144848/article/details/91925669
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。