您的位置:首页 > 其它

返回可用的内存空间 和 返回总的内存空间

2016-08-18 00:18 246 查看
<span style="font-family:SimHei;font-size:32px;color:#FF0000;">返回可用的内存数 和 返回总的内存数:  </span>


/**
* @param ctx
* @return 返回可用的内存数 bytes
*/
public static long getAvailSpace(Context ctx){
//1,获取activityManager
ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
//2,构建存储可用内存的对象
MemoryInfo memoryInfo = new MemoryInfo();
//3,给memoryInfo对象赋(可用内存)值
am.getMemoryInfo(memoryInfo);
//4,获取memoryInfo中相应可用内存大小
return memoryInfo.availMem;
}

/**
* @param ctx
* @return 返回总的内存数 单位为bytes 返回0说明异常
*/
public static long getTotalSpace(Context ctx){
/*//1,获取activityManager
ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
//2,构建存储可用内存的对象
MemoryInfo memoryInfo = new MemoryInfo();
//3,给memoryInfo对象赋(可用内存)值
am.getMemoryInfo(memoryInfo);
//4,获取memoryInfo中相应可用内存大小
return memoryInfo.totalMem;*/

//内存大小写入文件中,读取proc/meminfo文件,读取第一行,获取数字字符,转换成bytes返回
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
fileReader= new FileReader("proc/meminfo");
bufferedReader = new BufferedReader(fileReader);
String lineOne = bufferedReader.readLine();
//将字符串转换成字符的数组
char[] charArray = lineOne.toCharArray();
//循环遍历每一个字符,如果此字符的ASCII码在0到9的区域内,说明此字符有效
StringBuffer stringBuffer = new StringBuffer();
for (char c : charArray) {
if(c>='0' && c<='9'){
stringBuffer.append(c);
}
}
return Long.parseLong(stringBuffer.toString())*1024;
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(fileReader!=null && bufferedReader!=null){
fileReader.close();
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐