Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android bitmaps in xml leak memory?

Here are some newbie memory management observations to which I would like hear an experienced opinion.

It seems that setting android:backgound="@drawable/xyz" in a xml layout causes memory loss in my app. The respective activities keep stacking up until I get an OOM error. This is especially true if I rotate the device orientation.

However, if I load the same resource with setBackgoundResource(), and then clear the callback and set the background reference to null, there is no leak whatsoever.

that is, first in onCreate()

    mMainLayout.setBackgroundResource(R.drawable.background_general_android);

and then in onDestroy()

mMainLayout.getBackground().setCallback(null);
mMainLayout.setBackgroundDrawable(null);

Is this roughly correct, or am I missing something essential?

like image 552
perza Avatar asked Nov 13 '22 05:11

perza


1 Answers

This would only happen if you keep a copy of the drawables in a static cache for instance. You might also be leaking your activities and setting the drawables to null simply hides the problem for a little longer. You should use a tool like MAT to inspect the content of your heap and figure out what's going on.

like image 108
Romain Guy Avatar answered Nov 16 '22 02:11

Romain Guy