I recently found out how much memory could be wasted due to a context leak and how to test such leaks with a memory dump after changing the screen orientation. A new activity must be created and created, the original destroyed and assembled. However, if I do not miss the memory and do not see it, the activity below is not going to be collected if it starts various activities 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 is the information about the memory dump made after pressing the button to start the panel and request garbage collection several 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 adding an extra finish between actions would make the first one available for collection and allow me to check for leaks in an additional way, is this reasonable? Am I a memory leak? Is there any reason Android wants to keep this shattered activity?
source share