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:
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());
}
}
public class Bar extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("hello, world");
setContentView(textView);
}
}
Here's the memory dump info, taken after clicking the button to start Bar and requesting garbage collection a few times:
Class Name | Shallow Heap | Retained Heap
----------------------------------------------------------------------------------------
com.test.testProject.Foo @ 0x4135b188 | 184 | 2,208
mOuterContext android.app.ContextImpl @ 0x4135b390 | 96 | 392
<Java Local> java.lang.Thread @ 0x40996460 main Thread| 80 | 1,416
mContext android.media.AudioManager @ 0x4135b480 | 48 | 176
----------------------------------------------------------------------------------------
Based on this, 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?