I found the article "Avoidance of memory leaks" , which says that the following code:
private static Drawable sBackground; @Override protected void onCreate(Bundle state) { super.onCreate(state); TextView label = new TextView(this); label.setText("Leaks are bad"); if (sBackground == null) { sBackground = getDrawable(R.drawable.large_bitmap); } label.setBackgroundDrawable(sBackground); setContentView(label); }
not a good idea, because:
When you change the screen orientation to the default system, destroy the current activity and create a new one, preserving its state. In this case, Android will reload the application user interface from resources.
So the above code:
... leak of the first activity created when the screen orientation was first changed. When a Drawable is attached to a view, the view is set as a callback to the selected one. In the code snippet above, this means that drawable has a link to the TextView, which itself has a link to the activity (Context), which in turn has links (depending on your code.)
But when the screen orientation changes, the setBackgroundDrawable (Drawable background) method is called , which, in turn, calls:
background.setCallback(this);
The Drawable.setCallback() method is defined as follows:
public final void setCallback(Callback cb) { mCallback = new WeakReference<Callback>(cb); }
So, now the background should release the old link to the previous TextView, and a new link to the new TextView should be created.
So, it seems that changing the screen orientation of the link leak only until the activity is created.
Where am I going wrong?