Note that there are some explanatory texts on larger screens.

plurals
  1. POProper onDestroy() / How to avoid memory leaks
    primarykey
    data
    text
    <p>I read a number of articles on how to avoid memory-leaks in Android, but i'm still not quite sure if I got it right.</p> <ol> <li>My Application consists of a single <code>Activity</code>.</li> <li>I don't have any private or static members in that Activity, all code is started from within <code>onCreate()</code>.</li> <li>In have some self-contained static classes whose static instances sometimes hold references to a <code>Context</code> or <code>View</code>s. In my <code>onDestroy()</code> method, I set all of these instances to null.</li> <li>I recycle all of my <code>Bitmap</code>s.</li> </ol> <p><strong>Q1</strong>: Is that enough? </p> <p>What confuses me is the classic example of a no-go you can find on the net (<a href="http://www.curious-creature.org/2008/12/18/avoid-memory-leaks-on-android/" rel="noreferrer">http://www.curious-creature.org/2008/12/18/avoid-memory-leaks-on-android/</a>):</p> <pre><code>@Override protected void onCreate(Bundle state) { super.onCreate(state); TextView label = new TextView(this); label.setText("Leaks are bad"); setContentView(label); } </code></pre> <p>I thought that, as soon as <code>onCreate</code> finishes, <code>label</code> goes out of scope and is GCed. </p> <p><strong>Q2</strong>: How can this create a memory-leak?</p> <p>My Activity basically looks like this:</p> <pre><code>@Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* Statics */ AssetUtils.initIndex(this); BitmapLoader.startInstance(this); /* frame */ ViewGroup frame = (ViewGroup) getLayoutInflater().inflate(R.layout.frame, null); this.setContentView(frame); /* create controller */ Controller controller = new Controller(frame, getLayoutInflater()); /* START */ controller.start(); } @Override public void onDestroy() { super.onStop(); /* Statics */ AssetUtils.destroyInstance(); BitmapLoader.destroyInstance(); } </code></pre> <p>Inside <code>Controller</code> I occasionally retrieve a <code>Context</code> using <code>View#getContext()</code> to pass it to manually created <code>View</code>s and the like. It's never stored statically somewhere, only in member-variables of classes which all go back to <code>Controller</code>. </p> <p><strong>Q3</strong>: Is there something I overlooked?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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