获取U盘的真实路径
直接上代码(实测Android7.1.2有效)
public static String getUPath(Context context){
StorageManager mStorageManager = (StorageManager) context.getSystemService(Activity.STORAGE_SERVICE);
Class<?> volumeInfoClazz = null;
Method getVolumes = null;
Method isMountedReadable = null;
Method getType = null;
Method getPath = null;
List<?> volumes = null;
try {
volumeInfoClazz = Class.forName("android.os.storage.VolumeInfo");
getVolumes = StorageManager.class.getMethod("getVolumes");
isMountedReadable = volumeInfoClazz.getMethod("isMountedReadable");
getType = volumeInfoClazz.getMethod("getType");
getPath = volumeInfoClazz.getMethod("getPath");
volumes = (List<?>) getVolumes.invoke(mStorageManager);
if (volumes.size()==0){
return null;
}
for (Object vol : volumes) {
if (vol != null && (boolean) isMountedReadable.invoke(vol) && (int) getType.invoke(vol) == 0) {
File path2 = (File) getPath.invoke(vol);
String p2 = path2.getPath();
Log.i("zbh","找到U盘路径:%s\n",p2);
return p2;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}