1. 存储服务StorageManagerService 里面有一个被隐藏的方法getVolumeList()可以获取挂载设备列表
2. android.os.storage.StorageVolume 就是用来表示每个挂载设备的类,可以获取到很多挂载设备的信息,但是很多信息是隐藏的
3. 可以通过StorageVolume的getDescription()方法来区分USB和SD卡
4. 所以必须要用反射来调用有关方法
/**
* 通过判断挂载路径能否移除确定外置SD卡是否存在
*
* @param mContext
* @return
*/
private static String getExtendedMemoryPath(Context mContext) {
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 getDescription = storageVolumeClazz.getMethod("getDescription", Context.class);
Object result = getVolumeList.invoke(mStorageManager);
final int length = Array.getLength(result);
for (int i = 0; i < length; i++) {
Object storageVolumeElement = Array.get(result, i);
String path = (String) getPath.invoke(storageVolumeElement);
boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
String descprition = (String) getDescription.invoke(storageVolumeElement, mContext);
if (removable && descprition.contains("SD")) {
return path;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}