对于在Android开发过程中出现的内存泄露问题,google已经提供了dump heap profiling方法,生成profile之后,我们可以通过MAT 工具进行分析,这样可以帮助我们快速定位可能发生内存泄露的位置。
1. dump heap profile
Android的VM heap profiling发展到Android gingerbread版本,操作方法与之前的版本有所不同,详细差异请见:
http://www.milk.com/kodebase/dalvik-docs-mirror/docs/heap-profiling.html
下面介绍两种在gingerbread上dump heap profiling和的方法:
1.1 先选中某个要dump的进程,点击status bar上第二个按钮,即可Dump HPROF file
1.2 在Android Souce Code中编译时打开WITH_HPROF 和 WITH_HPROF_STACK
/* Set DUMP_HEAP_ON_DDMS_UPDATE to 1 to enable heap dumps
* whenever DDMS requests a heap update (HPIF chunk).
* The output files will appear in /data/misc, which must
* already exist.
* You must define "WITH_HPROF := true" in your buildspec.mk
* and recompile libdvm for this to work.
*
* To enable stack traces for each allocation, define
* "WITH_HPROF_STACK := true" in buildspec.mk. This option slows down
* allocations and also requires 8 additional bytes per object on the
* GC heap.
*/
注意:在生成heap profile之前,我们还需要修改/data/misc权限 chmod 777 /data/misc
2. 将Android heap PROF 转换成MAT可以分析的标准格式
hprof-conv source.hprof dest.hprof
3. 在Eclipse安装MAT,并分析heap dumps
我们从下面的站点下载MAT工具:
http://www.eclipse.org/mat/downloads.php
或者在Eclipse Help/Install New Software/ Add...中添加 update Site:http://download.eclipse.org/mat/1.1/update-site/
4. 使用MAT工具打开转换过的dest.hprof文件