环境 Android Studio 4.1
利用 AS 自带工具分析内存分配情况
一 打开分析工具 Profiler
- 可以在 Help 中搜索关键字 Profiler
- 可以直接找到 View - Tool Windows - Profiler
- 打开过一次后,在底部直接打开

二 Profiler 界面
右键底部的 Profiler tab,可以选择 View Mode,设置为 Windows 模式,独立成窗口模式,比较容易看(而且开发的一般有两个屏幕,把 Profile 窗口放到另外一个屏幕刚好一个屏幕看代码,一个屏幕看 Profiler 工具分析窗口)


三 开始录制分析内容
选择目标进程(或者打开 Profiler 工具,直接 Run 项目,就自动选择为当前 Run 的进程)








接下来抓大头的分析各个线程的情况时,可以看到 6699 分配了 64次,总大小 29M多,然后查看该线程的任务,以排查代码中的问题(给线程起个名字是多么重要哇~)
四 一个例子
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
testThread.start();
}
private Thread testThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
allocMethod();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "alloc_thread");
private byte[] allocMethod() {
Log.d("test", "allocMethod:");
return new byte[(int) (1024 * 10)];
}

五 最后
其实对象分配内存的次数可以有效分析一些内存问题,比如内存抖动等问题
当然,写个例子用来分析是非常简单的,但是实际项目中的问题定位起来肯定会异常地困难,这里的主要目的是解释如何使用这个工具进行分析而已。
网友评论