Android 7.0以上和7.0以下获取USB,sdcard路径的方法

1 7.0以上路径获取方法

   public static List getAllExternalSdcardPath(Context context) {
        List uDisks = new ArrayList<>();
        String systemPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        StorageManager mStorageManager;
        mStorageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        //获取所有挂载的设备(内部sd卡、外部sd卡、挂载的U盘)
        if (mStorageManager != null) {
            List<StorageVolume> volumes = mStorageManager.getStorageVolumes();
            Log.e("MainActivity", "size:" + volumes.size());
            if (volumes.size() > 0) {
                try {
                    Class storageVolumeClazz = Class
                            .forName("android.os.storage.StorageVolume");
                    //通过反射调用系统hide的方法
                    Method getPath = storageVolumeClazz.getMethod("getPath");
                    Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
                    for (int i = 0; i < volumes.size(); i++) {
                        StorageVolume storageVolume = volumes.get(i);//获取每个挂载的StorageVolume
                        //通过反射调用getPath、isRemovable
                        String storagePath = (String) getPath.invoke(storageVolume);//获取路径
                        if (!storagePath.equalsIgnoreCase(systemPath)) {
                            uDisks.add(storagePath);
                        }
                        boolean isRemovableResult = (boolean) isRemovable.invoke(storageVolume);//是否可移除
                        String description = storageVolume.getDescription(context);
                        Log.e("MainActivity", " i=" + i + " ,storagePath=" + storagePath
                                + " ,isRemovableResult=" + isRemovableResult + " ,description=" + description);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return uDisks;
    }

2 7.0以下获取路径的方法

public static List getUSBPaths(Context context) {//反射获取路径
        String[] paths = null;
        List<String> data = new ArrayList<>();// include sd and usb devices
        StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        try {
            paths = (String[]) StorageManager.class.getMethod("getVolumePaths", null).invoke(storageManager, null);
            for (String path : paths) {
                String state = (String) StorageManager.class.getMethod("getVolumeState", String.class).invoke(storageManager, path);
                if (state.equals(Environment.MEDIA_MOUNTED) && !path.contains("emulated")) {
                    Log.e("MainActivity", "路径---------->" + path);
                    data.add(path);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

你可能感兴趣的:(android)