前言
有获取外部SD卡存储空间的需求,但是某度出来的方法都千篇一律采用Environment类的getExternalStorageDirectory方法,但是此方法Deprecated。所以只能用其他方式。
获取StorageManager的实例
storageManager = (StorageManager)mContext.getSystemService(mContext.STORAGE_SERVICE);
private String[] getExtSDCardPath() {
Log.d("SDRemount ","getExtSDCardPath");
try {
Class<?>[] paramClasses = {};
Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", paramClasses);
getVolumePathsMethod.setAccessible(true);
Object[] params = {};
Object invoke = getVolumePathsMethod.invoke(storageManager, params);
return (String[])invoke;
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
返回挂载的SD卡路径,经多次测试,上一步获取到的路径全都为挂载的。其中第一个路径为:/storage/emulated/0,其为本身内部存储。所以当返回的路径个数大于1时,存在外部存储。
public String[] sdCardRemounted()
{
Log.d("SDRemount ","sdCardRemounted checked");
String[] data = getExtSDCardPath();
List<String> list =new ArrayList<>();
if (data.length > 0){
for(String path : data){
if(checkMounted(mContext,path)){
list.add(path);
}
}
}
int count = list.size();
String[] result =new String[count];
/*for (int i = 0;i < count; i++)
{
result[i]=list.get(i);
}*/
return list.toArray(result);
}
检查挂载:
private boolean checkMounted(Context context, String mountPoint) {
if (mountPoint == null) {
Log.d("SDRemount ","mountPoint == null");
return false;
}
//StorageManager storageManager = (StorageManager) context
//.getSystemService(Context.STORAGE_SERVICE);
try {
Method getVolumeState = storageManager.getClass().getMethod(
"getVolumeState", String.class);
String state = (String) getVolumeState.invoke(storageManager,
mountPoint);
//Log.d("SDRemount ","SDCard path " + mountPoint +" and state " +state);
StatFs statFs = new StatFs(mountPoint);
long blockSize=statFs.getBlockSizeLong();
long availableSize=statFs.getAvailableBlocksLong();
long totalSize=statFs.getBlockCountLong();
Log.d("SDRemount ","SDCard path " + mountPoint +" and state " +state +
" total size "+ totalSize*blockSize + " available size " + availableSize*blockSize);
return Environment.MEDIA_MOUNTED.equals(state);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public long getTotalSize(String path){
StatFs statFs = new StatFs(path);
long blockSize=statFs.getBlockSizeLong();
//long availableSize=statFs.getAvailableBlocksLong();
long totalSize=statFs.getBlockCountLong();
long total = blockSize * totalSize;
Log.d("SDRemount ","SDCard path " + path +" total size "+ total);
return total;
}
public long getAvailableSize(String path){
StatFs statFs = new StatFs(path);
long blockSize=statFs.getBlockSizeLong();
long availableSize=statFs.getAvailableBlocksLong();
//long totalSize=statFs.getBlockCountLong();
long total = blockSize * availableSize;
Log.d("SDRemount ","SDCard path " + path +" total size "+ total);
return total;
}