Android获取外置SD卡路径

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40391500/article/details/79676061

SD卡路径没有找到直接获取的方法,现在移植Android7.1的系统,以前在Android5.1上的应用不能直接用了
Android7.1换一张SD卡,路径又变了

兼容获取SD卡路径

//遍历storage路径下的所有文件
/****获取SD卡路径****/
    public String getSDCardPath(){
        String path = "";
        try {
            File file = new File("storage");
            if (file.exists()){
                String []list;
                list = file.list();
                if (list == null) return "";
                for (int i = 0; i < list.length; i++) {
                    if (list[i].indexOf("-") > 0){
                        path = "/storage/" + list[i];
                        break;
                    }else if (!"emulated".equals(list[i]) && !"self".equals(list[i])){
                        path = "/storage/" + list[i];
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("SD卡路径==========path is =========== " + path );
        Log.e("SD卡路径", "path is === " + path );
        return path;
    }

//7.0以上版本
public String externalSDCardPath() {
        try {
            StorageManager storageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
            // 7.0才有的方法
            List<StorageVolume> storageVolumes = storageManager.getStorageVolumes();
            Class<?> volumeClass = Class.forName("android.os.storage.StorageVolume");
            Method getPath = volumeClass.getDeclaredMethod("getPath");
            Method isRemovable = volumeClass.getDeclaredMethod("isRemovable");
            getPath.setAccessible(true);
            isRemovable.setAccessible(true);
            for (int i = 0; i < storageVolumes.size(); i++) {
                StorageVolume storageVolume = storageVolumes.get(i);
                String mPath = (String) getPath.invoke(storageVolume);
                Boolean isRemove = (Boolean) isRemovable.invoke(storageVolume);
                Log.d("tag2", "mPath is === " + mPath + "isRemoveble == " + isRemove);
            }
        }catch (Exception e){
            Log.d("tag2","e == "+e.getMessage());
        }
        return "";
    }

猜你喜欢

转载自blog.csdn.net/weixin_40391500/article/details/79676061
0条评论
添加一条新回复