------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();
}
}
