title: Testing for memory leaks in Android applications
body: <p>I've recently learned how much memory can be wasted by leaking context and how to test for such leaks with a memory dump after a screen orientation change. The new activity should be instantiated and created, the original destroyed and collected. However, unless I'm leaking memory and don't see it, the activity below doesn't seem to be collected if it starts a different activity and destroys itself:</p>
  
  <pre><code>public class Foo extends Activity {
      private Button button;
  
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
  
          button = new Button(this);
          button.setOnClickListener(new OnClickListener() {
              public void onClick(View view) {
                  startActivity(new Intent(Foo.this, Bar.class));
                  finish();
              }
          });
  
          setContentView(button);
      }
  
      protected void onDestroy() {
          super.onDestroy();
  
          button.setOnClickListener(null);
  
          Log.e("you're it", "isFinishing() == " + isFinishing());
      }
  }
  </code></pre>
  
  <p>&nbsp;</p>
  
  <pre><code>public class Bar extends Activity {
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
  
          TextView textView = new TextView(this);
          textView.setText("hello, world");
  
          setContentView(textView);
      }
  }
  </code></pre>
  
  <p>Here's the memory dump info, taken after clicking the button to start Bar and requesting garbage collection a few times:</p>
  
  <pre><code>Class Name                                               | Shallow Heap | Retained Heap
  ----------------------------------------------------------------------------------------
  com.test.testProject.Foo @ 0x4135b188                    |          184 |         2,208
   mOuterContext android.app.ContextImpl @ 0x4135b390      |           96 |           392
    &lt;Java Local&gt; java.lang.Thread @ 0x40996460  main Thread|           80 |         1,416
    mContext android.media.AudioManager @ 0x4135b480       |           48 |           176
  ----------------------------------------------------------------------------------------
  </code></pre>
  
  <p>Based on <a href="https://stackoverflow.com/questions/6108830/android-does-ondestroy-or-finish-actually-kill-the-activity">this</a>, I thought that throwing an extra finish between activities would make the first one eligible for collection and allow me to test for leaks an additional way, is this sensible? Am I leaking memory? Is there some reason Android would want to keep this destroyed activity around?</p>