- andorid中获取内置SD卡和外置SD卡
public String getSdPath(Context context,boolean isOut){
String sdpath=null;
if (Build.VERSION.SDK_INT>23){
try {
StorageManager sd_storageManager= (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
Method volumnlist=sd_storageManager.getClass().getMethod("getVolumeList");
Class sd_storagevolume=Class.forName("android.os.storage.StorageVolume");
Method isRemovable=sd_storagevolume.getMethod("isRemovable");
Method getPath=sd_storagevolume.getMethod("getPath");
Object volumes=volumnlist.invoke(sd_storageManager);
int index= Array.getLength(volumes);
for (int i=0;i<index;i++){
Object volume=Array.get(volumes,i);
String path= (String) getPath.invoke(volume);
boolean isOutSd= (boolean) isRemovable.invoke(volume);
if (isOutSd==isOut){
//外部存储
sdpath= path;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}else{
String inpath= System.getenv("EXTERNAL_STORAGE"); //内置sd路径
String outpath=System.getenv("SECONDARY_STORAGE");
if (isOut){
sdpath=outpath;
}else{
sdpath=inpath;
}
}
return sdpath;
}
1. 在sdk小于于23版本时:
- String inpath= System.getenv(“EXTERNAL_STORAGE”)获取内置sd卡,和系统的 Environment.getExternalStorageDirectory().getAbsolutePath()获取的结果是一样的
- String outpath=System.getenv(“SECONDARY_STORAGE”);获取外置sd卡,
- 当sdk>=23时:
- 由于谷歌把SECONDARY_STORAGE这个值给去掉了所以会行不通,所以研究源码,
在Eventment中
public static File getExternalStorageDirectory() {
throwIfUserRequired();
return sCurrentUser.getExternalDirs()[0];
}
获取SD卡路径,看看getExternalDirs()这个方法
public File[] getExternalDirs() {
final StorageVolume[] volumes = StorageManager.getVolumeList(mUserId,
StorageManager.FLAG_FOR_WRITE);
final File[] files = new File[volumes.length];
for (int i = 0; i < volumes.length; i++) {
files[i] = volumes[i].getPathFile();
}
return files;
}
这个方法获取所有的存储的列表,查看StorageManager这个类找到getVolumeList这个方法,我们使用没有参数的方法由于是掩藏方法,所以要通过反射方法拿到列表
/** {@hide} */
public @NonNull StorageVolume[] getVolumeList() {
return getVolumeList(mContext.getUserId(), 0);
}
再来看看StorageVolume这个类,
/**
* Returns the mount path for the volume.
*
* @return the mount path
*/
public String getPath() {
return mPath.toString();
}
这个方法是获取存储设备的路径,由于这个类是掩藏类,所以用反射方法获取,最后判断是否事内置SD还是外置SD通过StorageVolume的方法:
/**
* Returns true if the volume is removable.
*
* @return is removable
*/
public boolean isRemovable() {
return mRemovable;
}
判断是否可移除,如果可移除就是外置SD卡,这个方法同样需要反射