获取系统内存信息
1. 获取当前手机可用内存
public static String getAvailSpace(Context context) {
//1, 获取ActivityManager对象
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context
.ACTIVITY_SERVICE);
//2, 创建MemoryInfo对象,用于待会儿获取内存的数据
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
//3, 获取内存数据,并将数据放到memoryInfo中
activityManager.getMemoryInfo(memoryInfo);
//4, 将获取的内存大小规格化(KB,MB,GB) 哪个规格合适就用哪个
return Formatter.formatFileSize(context, memoryInfo.availMem);
}
复制代码
2. 获取当前手机总共的内存大小
public static String getTotalSpace(Context context) {
/*-----------方式1:适用于API16及以上Android设备----------*/
/*//1, 获取ActivityManager对象
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context
.ACTIVITY_SERVICE);
//2, 创建MemoryInfo对象,用于待会儿获取内存的数据
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
//3, 获取内存数据,并将数据放到memoryInfo中
activityManager.getMemoryInfo(memoryInfo);
//4, 将获取的内存大小规格化(KB,MB,GB) 哪个规格合适就用哪个 memoryInfo.totalMem是API16之后才有的
return Formatter.formatFileSize(context, memoryInfo.totalMem);*/
/*-----------方式2:适用于所有Android设备----------*/
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
//1, 读取Android设备的内存信息文件内容
fileReader = new FileReader(MEMINFO_PATH);
bufferedReader = new BufferedReader(fileReader);
//2, 文件的第一行就是当前手机的总内存信息(单位是kb)
String memTotal = bufferedReader.readLine();
LogUtil.d(TAG,"第一行的内容是:"+memTotal);
//3, 替换掉非数字内容
memTotal = memTotal.replaceAll("[^0-9.,]+", "");
//4, 转换为M或G 返回
return Formatter.formatFileSize(context, Long.parseLong(memTotal)*1024);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "0M";
}
复制代码