首页  编辑  

判断外置存储卡SD card是否存在并返回路径

Tags: /Android/   Date Created:

/**
* 通过反射调用获取内置存储和外置sd卡根路径(通用)
*
* @param mContext 上下文
* @param is_removale 是否可移除,false返回内部存储路径,true返回外置SD卡路径
* @return
*/
private static String getStoragePath(Context mContext, boolean is_removale) {
String path;
//使用getSystemService(String)检索一个StorageManager用于访问系统存储功能。
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 getState = mStorageManager.getClass().getMethod("getVolumeState", String.class);
Object result = getVolumeList.invoke(mStorageManager);

for (int i = 0; i < Array.getLength(result); i++) {
Object storageVolumeElement = Array.get(result, i);
path = (String) getPath.invoke(storageVolumeElement);
String state = (String) getState.invoke(mStorageManager, path);
boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
File file = new File(path);
StatFs stat = new StatFs(path);
String fs = getFileSystem(file);
if (stat.getTotalBytes() > 1000 * 1000 * 128 && file.canWrite() && is_removale == removable
&& state.equals(Environment.MEDIA_MOUNTED) && !fs.equals("tmpfs")) {
return path;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}

public static String getFileSystem(File path) {
try {
Process mount = Runtime.getRuntime().exec("mount");
BufferedReader reader = new BufferedReader(new InputStreamReader(mount.getInputStream()));
mount.waitFor();

String line;
while ((line = reader.readLine()) != null) {
String[] split = line.split("\\s+");
for (int i = 0; i < split.length - 1; i++) {
if (!split[i].equals("/") && path.getAbsolutePath().startsWith(split[i]))
return split[i + 1];
}
}
reader.close();
mount.destroy();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return null;
}