展开全部

1.方法一


//内置sd卡路径String sdcardPath = System.getenv("EXTERNAL_STORAGE"); //内置sd卡路径String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();//外置置sd卡路径String extSdcardPath = System.getenv("SECONDARY_STORAGE");

在Enviroment类的源码中获得sd卡路径其实也是通过32313133353236313431303231363533e4b893e5b19e31333365666230 System.getnv() 方法来实现的,如隐藏的方法:

/** {@hide} */public static File getLegacyExternalStorageDirectory() {

return new File(System.getenv(ENV_EXTERNAL_STORAGE));}

注:更详细的内容还是去看Enviroment源码。

另外要注意的是,在API 23版本中 SECONDARY_STORAGE 被移除。

2.方法二


代码如下:

private static String getStoragePath(Context mContext, boolean is_removale) {
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");
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);
if (is_removale == removable) {
return path;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;}