Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Drawables memory leak

I work with several large drawables and I don't know how to manage memory leaks. I tracked the heap size of my application and it doesn't stop to grow (as the allocated memory).

It is especially the "byte array (byte[])" type which grows up and never decrease. (in the DDMS Heap view on Eclipse)

My application is composed of one activity which uses fragments. Those fragments are displaying several large images. I tried to set drawables callback to null, set drawables to null, clear my volatile cache (which prevent my app from doing too many disk IO) when I pop back a fragment but the heap never decrease.

In fact, each time I call : Drawable.createFromResourceStream(context.getResources(), value, new FileInputStream(f), f.getName(), opts); the heap grows up. How can I free memory ?

Thanks !

like image 732
abecker Avatar asked Sep 15 '12 14:09

abecker


2 Answers

A memory leak happens when Java finds objects in the memory that are referenced by your code which is preventing the Garbage Collector from freeing this memory. A common cause in Android is referencing the Activity context rather than the Application context. Make sure your context references the Application (i.e. use getApplicationContext rather than using this. Check this video for explanation on Memory leaks and also check this question.

like image 93
Mohamed_AbdAllah Avatar answered Oct 04 '22 11:10

Mohamed_AbdAllah


The question seems answered but a post by Romain Guy seems relevant to get more info: Avoiding Memory Leaks.

Apparently, if you (for example) set a drawable as a background image to a text view by using setBackgroundDrawable* (thus attaching the drawable to the view) then change the orientation (destroying the Activity and redrawing the UI) the drawable will still have access to the old activity (after the old activity's destruction), thus creating a memory leak.

*(as a side note - setBackgroundDrawable has been deprecated since API level 16)

like image 28
studiou Avatar answered Oct 04 '22 09:10

studiou