要在 API 16 之前执行此操作,您必须阅读 android 内核的 proc/meminfo 文件:
public long getTotalMemory() {
String str1 = "/proc/meminfo";
String str2;
String[] arrayOfString;
long initial_memory = 0;
try {
FileReader localFileReader = new FileReader(str1);
BufferedReader localBufferedReader = new BufferedReader( localFileReader, 8192);
str2 = localBufferedReader.readLine();//meminfo
arrayOfString = str2.split("\\s+");
for (String num : arrayOfString) {
Log.i(str2, num + "\t");
}
//total Memory
initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;
localBufferedReader.close();
return initial_memory;
}
catch (IOException e)
{
return -1;
}
}
来源:这个问题
但是,在 API 16 及更高版本中,您可以使用以下代码来检索总内存:
ActivityManager actManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
MemoryInfo memInfo = new ActivityManager.MemoryInfo();
actManager.getMemoryInfo(memInfo);
long totalMemory = memInfo.totalMem;