Android程序为了排查性能问题,或者做APM,需要监控内存信息,有如下两个方法可以得到内存信息。

使用ActivityManager类获取系统内存信息

ActivityManager类提供了获取系统内存信息的功能。你可以通过调用ActivityManager.getMemoryInfo()方法来获取内存信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);

long totalMemory = memoryInfo.totalMem; // 总内存
long availableMemory = memoryInfo.availMem; // 可用内存

Log.d("MemoryInfo", "Total Memory: " + totalMemory + " bytes");
Log.d("MemoryInfo", "Available Memory: " + availableMemory + " bytes");
}
}

读取/proc/meminfo文件

Android系统提供了一个名为/proc/meminfo的文件,其中包含了详细的内存信息。你可以通过读取这个文件来获取手机的总内存和可用内存等信息。
但是该方法需要时系统app才有这个权限,需要注意。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class MemoryInfoUtil {
public static String getTotalMemory() {
String memInfoPath = "/proc/meminfo";
String totalMemory = "";
try (BufferedReader br = new BufferedReader(new FileReader(memInfoPath))) {
String line;
while ((line = br.readLine()) != null) {
if (line.contains("MemTotal:")) {
String[] splits = line.split("\\s+");
totalMemory = splits[1];
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return totalMemory.isEmpty() ? "0" : totalMemory;
}

public static String getAvailableMemory() {
String memInfoPath = "/proc/meminfo";
String availableMemory = "";
try (BufferedReader br = new BufferedReader(new FileReader(memInfoPath))) {
String line;
while ((line = br.readLine()) != null) {
if (line.contains("MemFree:")) {
String[] splits = line.split("\\s+");
availableMemory = splits[1];
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return availableMemory.isEmpty() ? "0" : availableMemory;
}
}