您的位置:首页 > 移动开发 > Android开发

android6.0通过反射获取USB和U盘以及内部存储路径,区分USB和U盘路径

2017-04-26 20:35 543 查看
------keyword是用来区分返回的是USB路径还是内部存储路径还是U盘路径

------主要还是storageVolume类(代表一个外挂设备)中的getUserLabel 这个方法,我们反射这个方法获取到的这个是当前存储设备的名称

public static String SD = "内部存储";
public static String EXT = "SD";
public static String USB = "盘";

----这三个便是传参数时keyword

public static String getStoragePath(Context mContext,String keyword) {
String resultpath = "";
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");

// Method[] getDescriptionId = storageVolumeClazz.getDeclaredMethods();

// String content = "";

// for (int i = 0; i < getDescriptionId.length; i++) {
// Method method = getDescriptionId[i];
// String methodmname = method.getName();
// content += methodmname + "<><> " + "\r\n";
// }

Object result = getVolumeList.invoke(mStorageManager);

final int length = Array.getLength(result);

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

for (int i = 0; i < length; i++) {

Object storageVolumeElement = Array.get(result, i);

String userLabel = (String) getUserLabel.invoke(storageVolumeElement);

// content += userLabel + "<><> " + "\r\n";

String path = (String) getPath.invoke(storageVolumeElement);

if(userLabel.contains(keyword)){
resultpath = path;
}
// content += path + "<><> " + userLabel + "\r\n";

// boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
//
// if (is_removale == removable) {
//
// return path;
// }
}
// writeFile(content);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return resultpath;
}

//这个写文件的方法是测试的时候将反射获取的外置路径以及外置卡信息写入文件中方便我们查看

public static void writeFile(String content) {
try {
PrintStream ps = new PrintStream(new FileOutputStream(new File(
"/mnt/sdcard/path.txt")));
ps.append(content);// 往文件里写入字符串
ps.flush();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: