Android 7.1获取外置SD卡和USB路径的几种方式

在把Android4.4的代码移植到Android7.1的时候发现原来的SD卡路径不可用了,通过log日志的查看发现路径变成了/storage/7A40-AD28了,看见这个一脸懵逼啊,总感觉这个路径怪怪的。抱着疑惑的态度我又插了另外一张SD卡,谁知道路径又变了。这不是坑吗?

在网上找了一大堆的,发现这个的方法可行:https://blog.csdn.net/u010663758/article/details/51308282。、

1.采用反射的方式获取地址。

private static String getStoragePath(Context mContext, boolean is_removale) {  

      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");
            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);
                boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
                if (is_removale == 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;
}
2.通过系统自身的方法调用StorageManager的getVolumeList():
private String getSDPath(){
StorageManager mStorageManager=(StorageManager) getSystemService(SEARCH_SERVICE);
StorageVolume[] storageVolumeList = mStorageManager.getVolumeList(); 
if (storageVolumeList!=null) {
for (StorageVolume volume:storageVolumeList) {
String path=volume.getPath().;
if (path.contains("USB")) {
dirUsb=path;
return dirUsb;
}else if (path.contains("SD")) {
dirScard=path;
return dirScard
}
}
}
}

3.参照Android SystemUI源码的SD卡以及USB路径获取方式:

StorageManager mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
        List vols = mStorageManager.getVolumes();
        for (int i = 0; i < vols.length; i++) {
DiskInfo disk = vols.get(i).getDisk();
String path = vols.get(i).path;
boolean sd = false;
boolean usb = false;
if (disk != null) {
if (disk.isSd()) {
String sdPath = path;
}else if (disk.isUsb()) {
String usbPath = path;
}
}
}



你可能感兴趣的:(SD卡路径)