获取手机内存使用情况应该是很常用的了,不多说直接上代码
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//有SD卡
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
//内存是分块的 分别获取块的数量和每块的大小
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
long availableBlocks = stat.getAvailableBlocks();//可用内存块的数量
long totalSize = totalBlocks * blockSize;
long availSize = availableBlocks * blockSize;
long hasUsed = totalSize - availSize;
//格式化
totalStr = Formatter.formatFileSize(mActivity, totalSize);
availStr = Formatter.formatFileSize(mActivity, availSize);
hasUsedStr = Formatter.formatFileSize(mActivity, hasUsed);
} else {
//如果没有SD卡
File path2 = Environment.getDataDirectory();
StatFs stat2 = new StatFs(path2.getPath());
long blockSize2 = stat2.getBlockSize();
long totalBlocks2 = stat2.getBlockCount();
long availableBlocks2 = stat2.getAvailableBlocks();
long totalSize2 = totalBlocks2 * blockSize2;
long availSize2 = availableBlocks2 * blockSize2;
long hasUsed = totalSize2 - availSize2;
totalStr = Formatter.formatFileSize(mActivity, totalSize2);
availStr = Formatter.formatFileSize(mActivity, availSize2);
hasUsedStr = Formatter.formatFileSize(mActivity, hasUsed);
}
代码中注释的很清楚了,就不再解释了。有问题的欢迎提问。