Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you rotate the device, the same <em><code>MyActivity</code></em> class (or whatever name you gave it) is recreated, the callback is overwritten and the leak exists until the next GC. The problem lies when you navigate to another activity, keeping a reference to the old one. Today, this is mitigated because the <code>setCallback</code> now stores the callback in a <code>WeakReference</code> as you can see in <a href="https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/graphics/java/android/graphics/drawable/Drawable.java">current Drawable code</a>, but it was a strong reference <a href="https://android.googlesource.com/platform/frameworks/base/+/android-1.6_r1/graphics/java/android/graphics/drawable/Drawable.java">once</a> (search for <code>setCallback(Callback cb)</code>). <strong>Anyway, you're right, if you just look into one activity, the callback will be reset after rotating.</strong></p> <p><em>(edit, paragraph added):</em> For example: MainAcivity@1 is the first instance. When you rotate, it's destroyed and a new MainActivity@2 is created. At first, there's a leak, but as soon as <code>sDrawable</code> is reassigned, MainActivity@1 is free to be collected and there's no problem. Now suppose that, instead of rotating, you navigate away to SecondActivity. Now, <code>sDrawable</code> is just for <code>MainActivity</code> and still holds a reference to MainActivity@2, so it leaks.</p> <p>See this code:</p> <pre><code>package com.douglasdrumond.leaky; import android.os.Bundle; import android.app.Activity; import android.graphics.drawable.Drawable; import android.widget.TextView; public class MainActivity extends Activity { private static Drawable sBackground; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView label = new TextView(this); System.gc(); long memory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); label.setText("Memory: " + memory / 1024f); if (sBackground == null) { sBackground = getResources().getDrawable(R.drawable.large_bitmap); } label.setBackgroundDrawable(sBackground); setContentView(label); } } </code></pre> <p>Clearly, rotating doesn't increase memory usage.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload