Android 设备获取U盘路径

@TargetApi(Build.VERSION_CODES.N)

public static ListgetAllExternalSdcardPath(Context context) {

ListuDisks =new ArrayList<>();

String systemPath =Environment.getExternalStorageDirectory().getAbsolutePath();

StorageManager mStorageManager;

mStorageManager = (StorageManager)context.getSystemService(Context.STORAGE_SERVICE);

//获取所有挂载的设备(内部sd卡、外部sd卡、挂载的U盘)

    if (mStorageManager !=null) {

Listvolumes =mStorageManager.getStorageVolumes();

if (volumes.size() >0) {

try {

ClassstorageVolumeClazz =Class

                        .forName("android.os.storage.StorageVolume");

//通过反射调用系统hide的方法

                Method getPath =storageVolumeClazz.getMethod("getPath");

Method isRemovable =storageVolumeClazz.getMethod("isRemovable");

for (int i =0;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);

RYLogUtils.d(TAG," i=" +i +" ,storagePath=" +storagePath

                            +" ,isRemovableResult=" +isRemovableResult +" ,description=" +description);

}

}catch (Exception e) {

Log.d("jason"," e:" +e);

}

}

}

return uDisks;

}

7.0一下的版本可用一下方法实现:

public static List getUSBPaths(Context context) {//反射获取路径

    String[] paths =null;

List 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.d("caokang","路径---------->" +path);

data.add(path);

}

}

}catch (Exception e) {

e.printStackTrace();

}

return data;

}

你可能感兴趣的:(Android 设备获取U盘路径)