Memory leak detection with LeakCanary

Talking about memory leaks in Android makes my hair prick. If you haven’t check another post about how to use MAT (Memory analyzer tool), you should probably do it now. Of course, memory leak management is one of the things you should do last, after you have completed your whole process, but it is good to have it in mind. And it is even better to know something more about it if you are working on a graphics app. Bitmaps (as we all should know), take a lot of memory. And LeakCanary helps you detect them easily.

What is LeakCanary?

It is a library and an app that installs next to your app and watches your process. It does heap dumps every number of seconds and shows you the shortest path of dependencies which led to the memory leak.

How does it work?

Well, basically it displays an overlay like “Dumping your app memory. This make take a while. Brrr.”. After that if it detects a memory leak it displays a notification and when you click on it a detailed screen is displayed. You can see it dumped as a text file or shared to an error logger.

LeakCanary screenshot

How to understand the error?

So at the top is the root of the hierarchy of dependencies that led to a memory leak. At the bottom is probably your component that needed some dependency from the top. You should go step by step analyzing each point and checking if it can lead to a memory leak.

Be careful with anonymous classes

Well, using an anonymous class in Java does only one thing. It creates a real class at compile time with the class name like MyClass$1, OnClickListener$2 etc. And most anonymous classes tend to leak because they do things after the activity/fragment lifecycle has ended. Keep that in mind whenever you create an anonymous class.

More Info

Watch this video by the creator of LeakCanary from Square. It will give you great insight how memory leaks occur and how to handle them. Otherwise, read the article from the top.

You may also like...