1 获取外置SD卡的路径
由于现在大多数手机都是带有内存的,原本获取外置SD卡路径的方法Environment.getExternalStorageDirectory()
获取得到的是手机自身内存的根目录。那么我们要怎么来获取到外置SD卡的路径,首先需要判断是否挂载了sdk,同样的Environment.getExternalStorageState()这个方法判断的只是机身内存空间,需要额外写一个工具类进行判断。这里要用到的是java的反射机制,下面是代码:
public class SDMountUtil {
/**
* 判断是否挂载外置sd卡
* @param context
* @return
*/
public static boolean sdMounted(Context context){
boolean mounted=false;
StorageManager sm=(StorageManager)context.getSystemService(Context.STORAGE_SERVICE);
try {
Method getVolumList=StorageManager.class.getMethod("getVolumeList");
getVolumList.setAccessible(true);
Object []results=(Object[]) getVolumList.invoke(sm);
if(results!=null){
for(Object result:results){
Method mRemoveable=result.getClass().getMethod("isRemovable");
Boolean isRemovable=(Boolean) mRemoveable.invoke(result);
if(isRemovable){
Method getPath=result.getClass().getMethod("getPath");
String path=(String) getPath.invoke(result);
Method getState=sm.getClass().getMethod("getVolumeState", String.class);
String state=(String) getState.invoke(sm, path);
if(state.equals(Environment.MEDIA_MOUNTED)){
mounted=true;
break;
}
}
}
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.pr