Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I invoke GC using adb tools?

I want to test android apps' memory performance, and I want to get memory information automaticaly. I use 'adb shell dumpsys meminfo ...' to get memory infomation periodicaly. Now, I want to observe memory leak, how can I excute gc ? Just like "Cause GC" in DDMS. Thanks!

like image 521
efei Avatar asked Mar 18 '23 17:03

efei


2 Answers

From android studio, you can use Profiler tools. Simply add your app session on the profiler and click on Memory sections. then press the Force GC button on the header (indicated with Trash icon)

Profiler Force GC

like image 149
Hayi Nukman Avatar answered Mar 29 '23 14:03

Hayi Nukman


The DDMS debugger connects to the Dalvik VM over a socket. In response to a "Cause GC" command, it sends a "HPGC" packet (ie., HeaP GC), which ends up in the handleHPGC() method of the core/java/android/ddm/DdmHandleHeap.java class.

The handleHPGC() method simply calls the java.lang.Runtime.getRuntime().gc() method.

I think you could use the Java Debug Wire Protocol (JDWP) to write a simple (??? - I've never done this, so it might not be all that simple) program that will attach to the debug port for the application you're testing and invoke the garbage collector using that API.

As the Java docs say for java.lang.Runtime.gc():

The method System.gc() is the conventional and convenient means of invoking this method.

like image 37
Michael Burr Avatar answered Mar 29 '23 15:03

Michael Burr