#最新发现,国内外机型SD卡路径问题简直时可怕,各种无法兼容,目前根据网上资料
现已修改兼容一下版本:
-4.4,5.0,5.1,6.0版本,其中国内只测国5.1版本的,其他为国外机型,需要自测!
String currentDir;
String storagePath;
// 6.0以上版本进行测试路径
if (Build.VERSION.SDK_INT >Build.VERSION_CODES.LOLLIPOP_MR1) {
if (storagePath == null) {
//内置路径
currentDir =Environment.getExternalStorageDirectory().getAbsolutePath();
} else {
//外置路径
storagePath=getStoragePath(mActivity, true);
}
} else {
//6.0一下版本
if ( getPath().equals("/mnt/shell/emulated")) {
//内置路径
currentDir =Environment.getExternalStorageDirectory().getAbsolutePath();
} else {
storagePath=getPath();
}
}
##return 有外置sd卡返回/mnt/media_rw/sdcard1,无外置返回/mnt/shell/emulated!
public String getPath() {
String sdcard_path = null;
String sd_default = Environment.getExternalStorageDirectory()
.getAbsolutePath();
if (sd_default.endsWith("/")) {
sd_default = sd_default.substring(0, sd_default.length() - 1);
}
// 得到路径
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
if (line.contains("secure"))
continue;
if (line.contains("asec"))
continue;
if (line.contains("fat") && line.contains("/mnt/")) {
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
if (sd_default.trim().equals(columns[1].trim())) {
continue;
}
sdcard_path = columns[1];
}
} else if (line.contains("fuse") && line.contains("/mnt/")) {
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
if (sd_default.trim().equals(columns[1].trim())) {
continue;
}
sdcard_path = columns[1];
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sdcard_path;
}
public 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;
}