Reputation: 4617
Is there anyway we can monitor GC events as they happens in Android?
In Java, I believe we can listen to the events http://www.fasterj.com/articles/gcnotifs.shtml But java.lang.management APIs are not available in Android.
Upvotes: 10
Views: 2151
Reputation: 3476
Okay, it will be different for both dalvik and art..
basically you can instruct adb shell to record the GC events in a trace file..
art: https://source.android.com/devices/tech/dalvik/gc-debug.html
It might even be the same adb commands for both art and dalvik.
The memory monitor tool plugs into this when it displays that graphical chart of memory for you in android studio.
Progammatically, probably is harder..look at how FB did their performance tooling as I believe that they are doing the GC event counts from the native C/C++ side and collating them in a flatbuffer for their java side profiling tool code to access..
Upvotes: 3
Reputation: 5542
Why you want this listener. If you simply want to know if your app is running out of memory just check this:
Release memory as memory becomes tight
During any stage of your app's lifecycle, the onTrimMemory() callback also tells you when the overall device memory is getting low. You should respond by further releasing resources based on the following memory levels delivered by onTrimMemory():
TRIM_MEMORY_RUNNING_CRITICAL Your app is still running, but the system has already killed most of the processes in the LRU cache, so you should release all non-critical resources now. If the system cannot reclaim sufficient amounts of RAM, it will clear all of the LRU cache and begin killing processes that the system prefers to keep alive, such as those hosting a running service. Also, when your app process is currently cached, you may receive one of the following levels from onTrimMemory():
TRIM_MEMORY_BACKGROUND The system is running low on memory and your process is near the beginning of the LRU list. Although your app process is not at a high risk of being killed, the system may already be killing processes in the LRU cache. You should release resources that are easy to recover so your process will remain in the list and resume quickly when the user returns to your app.
Here is the reference link https://developer.android.com/training/articles/memory.html
Upvotes: 6