Memory management
Every Java developer has heard of the garbage collector (GC); this is a mechanism that automatically frees the resources in memory for us. On some occasions, we can prevent the garbage collector from freeing some resources; if the resources keep growing, we will inevitably see OutOfMemoryError
.
If this happens, we need to locate the leak and then stop it. In this section, we will take a look at how to locate the source of the problem and a series of good practices to prevent this from happening.
This is not something to look into only when an error has occurred; our app might have leaks, not big enough to be detected with a quick test, that can lead to an error in a device with a smaller memory heap. Therefore, it's good to do a quick check on the memory levels before releasing an app.
Detecting and locating leaks
Android Studio provides a quick way to check the memory status. At the bottom window, you will find a tab called Memory next to logcat
and the ADB logs.
If you click...