Understanding memory leaks in an Android application

I found the article "Avoidance of memory leaks" , which says that the following code:

private static Drawable sBackground; @Override protected void onCreate(Bundle state) { super.onCreate(state); TextView label = new TextView(this); label.setText("Leaks are bad"); if (sBackground == null) { sBackground = getDrawable(R.drawable.large_bitmap); } label.setBackgroundDrawable(sBackground); setContentView(label); } 

not a good idea, because:

When you change the screen orientation to the default system, destroy the current activity and create a new one, preserving its state. In this case, Android will reload the application user interface from resources.

So the above code:

... leak of the first activity created when the screen orientation was first changed. When a Drawable is attached to a view, the view is set as a callback to the selected one. In the code snippet above, this means that drawable has a link to the TextView, which itself has a link to the activity (Context), which in turn has links (depending on your code.)

But when the screen orientation changes, the setBackgroundDrawable (Drawable background) method is called , which, in turn, calls:

 background.setCallback(this); 

The Drawable.setCallback() method is defined as follows:

 public final void setCallback(Callback cb) { mCallback = new WeakReference<Callback>(cb); } 

So, now the background should release the old link to the previous TextView, and a new link to the new TextView should be created.

So, it seems that changing the screen orientation of the link leak only until the activity is created.

Where am I going wrong?

+6
source share
1 answer

You are absolutely right. However, there is one subtle point: an article from 2009. Then the implementation of setCallback was different :

Android <= 2.3.7:

 public final void setCallback(Callback cb) { mCallback = cb; } 

Android> = 4.0.1:

 public final void setCallback(Callback cb) { mCallback = new WeakReference<Callback>(cb); } 

Grepcode does not show the source code of the intermediate versions, it is the only diff that I could quickly find.


So, you are absolutely right in this particular case (if you aim> 14, that is). However, it is still very important to really think about what actually happens when you keep a static link to such items (like you). There are many cases where you, of course, can leak Context .

+11
source

Source: https://habr.com/ru/post/976381/


All Articles