最近需要处理SD卡容量显示,总结一下:
首先,在FileListManager.java构造函数中检测SD并取得路径:
<span style="white-space:pre"> </span>File path_SD;
StatFs statfs_sd = null;
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ //判读是否存在外置SD卡
path_SD = Environment.getExternalStorageDirectory(); //得到SD卡路径
statfs_sd = new StatFs(path_SD.getPath());
//if(statfs_sd != null){
long blockSize_sd = statfs_sd.getBlockSize();
long blockCount_sd = statfs_sd.getBlockCount();
long availCount_sd = statfs_sd.getAvailableBlocks();
mTotleMemory_sd += blockSize_sd*blockCount_sd;
mAvailMemory_sd += availCount_sd*blockSize_sd;
//}
}
其次,获取容量:
public long GetTotleSDSize_SD()
{
return mTotleMemory_sd;
}
public long GetTotleAvailSize_SD()
{
return mAvailMemory_sd;
}
接下来,将获取到</span>的容量作格式转换成MB或者GB:
public static String FormetFileSize(long fileS) {
if(fileS == 0)
{
return "0M";
}
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "K";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "M";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "G";
}
return fileSizeString;
}
最后, FormetFileSize(mTotleMemory_sd) 和 FormetFileSize(mAvailMemory_sd) 通过 testView 显示出来就OK了。。