第三方应用不能访问某些系统包中的类,采用反射方式实现
public static boolean isSDcardMounted(Context context) {
boolean isMounted = false;
StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
try {
Method getVolumList = StorageManager.class.getMethod("getVolumeList", null);
getVolumList.setAccessible(true);
Object[] results = (Object[])getVolumList.invoke(sm, null);
if (results != null) {
for (Object result : results) {
Method mRemoveable = result.getClass().getMethod("isRemovable", null);
Boolean isRemovable = (Boolean) mRemoveable.invoke(result, null);
LogUtil.d("[isSDcardMounted] isRemovable : " + isRemovable);
if (isRemovable) {
Method getPath = result.getClass().getMethod("getPath", null);
String path = (String) getPath.invoke(result, null);
LogUtil.d("[isSDcardMounted] path : " + path);
Method getPathFile = result.getClass().getMethod("getPathFile", null);
File sdPathFile = (File) getPathFile.invoke(result, null);
if (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(sdPathFile))) {
isMounted = true;
}
}
}
}
} catch (NoSuchMethodException e){
e.printStackTrace();
} catch (IllegalAccessException e){
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
LogUtil.d("[isSDcardMounted] isMounted : " + isMounted);
return isMounted;
}