// 获得可用空间 (运行内存 由于可能大于2g故此处使用long)
public static long getAvailSpace(Context context){
// 1 获得activity管理器
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//2 构建存储可用内存对象
ActivityManager.MemoryInfo memoryInfo= new ActivityManager.MemoryInfo();
// 给MemoryInfo对象赋值 (此处使用get进行赋值 不像以前的set进行赋值)
am.getMemoryInfo(memoryInfo);
// 返回可用的内存数 byte
return memoryInfo.availMem;
}
// 获得总的运行内存 至少api 16才能用 此方法安卓4.1 以下不可用 不能兼容低的版本
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public static long getTotalSpace(Context context) throws IOException {
// // 1 获得activity管理器
// ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// //2 构建存储可用内存对象
// ActivityManager.MemoryInfo memoryInfo= new ActivityManager.MemoryInfo();
// // 给MemoryInfo对象赋值 (此处使用get进行赋值 不像以前的set进行赋值)
// am.getMemoryInfo(memoryInfo);
// // 返回可用的内存数 byte // 1kb = 1024 byte
// return memoryInfo.totalMem;
/*每款手机的内存大小都有写入文件的 可以从写入的文件中读取
* 文件所在位置 DDMS - File Elporer-proc meminfo文件中(内存信息)(文件第一行就是)
* */
FileReader fileReader=null;
BufferedReader bufferedReader=null;
try {
fileReader = new FileReader("proc/meminfo");
bufferedReader =new BufferedReader(fileReader);
String LineOne= bufferedReader.readLine();
// 由于文件内容都是成行的 直接读取一行 得到的内容不能直接使用 故
char[] chars= LineOne.toCharArray();
//循环遍历每一个字符如果字符的ASCII值在0-9之间 说明次字符为有效字符
StringBuffer stringBuffer = new StringBuffer();
for(char c:chars){
if (c>='0'&&c<='9'){
stringBuffer.append(c);//满足条件开始拼接
}
}
return Long.parseLong(stringBuffer.toString())*1024 ;//在转换为字符串 字符串转化为数字
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//关 流
if(fileReader!=null && bufferedReader!=null){
try {
fileReader.close();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return 0;
}
网友评论