Reputation: 3362
In my application in every onDestroy I call this on the views, as I read it is a good practice for minimizing the OOM Exceptions.
public void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
The thing is, it's not really clear to me what
view.getBackground().setCallback(null)
exactly does. Is it enough to let it like this or should I also recycle the bitmaps of the backgrounds of the Views?
Upvotes: 1
Views: 113
Reputation: 29714
First part - to explain what setCallback(null)
does, you should look at what the "callback" refers to.
Drawable.Callback
is used when animating drawables. As per the online docs:
Implement this interface if you want to create an animated drawable that extends Drawable. Upon retrieving a drawable, use setCallback(android.graphics.drawable.Drawable.Callback) to supply your implementation of the interface to the drawable; it uses this interface to schedule and execute animation changes.
You are preventing any further animation callbacks by setting to null
. This removes any references that the Drawable
will contain to the Callback
objects.
If you don't remove these references, you could leak memory when you unbind your drawables.
Second part - should you recycle your bitmaps after this call? Yes. This call removes the links between your activity view and the drawables, but it does not reclaim the memory used by the drawables.
If you are writing for 2.3 and below, you should recycle the bitmaps. See page on Managing Bitmap Memory:
On Android 2.3.3 (API level 10) and lower, using recycle() is recommended. If you're displaying large amounts of bitmap data in your app, you're likely to run into OutOfMemoryError errors. The recycle() method allows an app to reclaim memory as soon as possible.
I see this code is used in many other questions, and some of the discussions may help future readers:
Upvotes: 1