Java – learn about memory leaks in Android Applications

I found the article "avoiding memory leaks", which says 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:

Then the above code:

However, when the screen direction changes, call the method setBackgroundDrawable (Drawable background), and then call:

background.setCallback(this);

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

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

Therefore, the background should now release the old reference to the previous textview and create a new reference to the new textview

Therefore, it seems that changing the screen orientation will only leak the reference until a new activity is created

What's wrong with me?

Solution

You are absolutely right However, there is a subtle point: the article comes from 2009 At that time, 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 display the source code of the intermediate version, which is the only difference I can quickly find

So, again, you are absolutely right in this particular case (if your goal is > 14) But when you keep static references to these projects (as you do), it's still important to really think about what actually happens There are many situations where you are sure to leak the context

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>