Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can I do to avoid memory leaks in my Android app?

My android app is taking more and more memory over time. I took a heap dump and analyzed it with MAT.

Here's the main leak suspect :

So it seems like one of my activities isn't cleared from memory after I quit the app (with back button) then when I restart the app a new instance is created and fills in the memory.

Now if they're PhantomReferences why the memory isn't cleared after a while or when I quit the app? The memory is never cleared even when I use other app etc. The only way to completely close the app is to use a task manager to manually kill the app.

What can I do to avoid this anarchic memory consumption ?

EDIT:

I found the problem! Each activity was setting up a CustomExceptionHandler with Thread.setDefaultUncaughtExceptionHandler() and that CustomExceptionHandler was keeping a reference to the context. So I got rid of the context reference and I 'nulled' the DefaultUncaughtExceptionHandler in the onDestroy() method. That's really better now!

like image 981
Alexis Avatar asked Dec 26 '22 22:12

Alexis


1 Answers

I would use the dominator tree functionality of MAT to find out what is above those references, this may give you an idea of which Activity is the culprit.

Make sure you haven't passed a Context anywhere and held a reference to it, this is a classic android memory leak and it's really easy to do!

Although some static analysis tools frown on this, in the onDestroy() methods of your Activity you can null all your local variables (except primitives), it helps to nudge the garbage collector sometimes and can make for an easier to analyse heap dump in MAT.

like image 99
ScouseChris Avatar answered Jan 12 '23 23:01

ScouseChris