Normally I always use Drawable resources in Imageviews because I haven’t to manually release them.
But in some cases I need to dynamically create bitmaps and then I’ve to manually call recycle() on them in onDestroy(). That’s the best solution I’ve found according to that other StackOverflow question.
I want to understand how Android manages Drawable resources and why I haven’t to manually recycle them. And when understood see if similar logic can be applied to manually created bitmaps.
A
Drawableis much more broad than aBitmap.Drawableis intended to represent anything the graphics system can render to the display. There are subclasses ofDrawable– such as asShapeDrawable, orColorDrawable– that do not containBitmaps and hence do not need any sort of manual memory management.A
BitmapDrawablewraps aBitmapand contains a reference to aBitmap. TheBitmapis special, because Android maintains the pixel data for allBitmapsin a separate heap, which is managed separately from the rest of your application. When the Android garbage collector cleans up aBitmapobject, it also cleans up the the pixel data from the bitmap heap. But you can force it to happen sooner by manually callingrecycle()on theBitmap, which marks theBitmapinvalid and releases its pixel data.Android allocates a fixed size bitmap heap for each running application, and it is possible for your app to exhaust its heap by leaving too many
Bitmaps in use at once. That’s why if your application uses bitmaps extensively, you will probably benefit from recycling bitmaps as soon as you know you won’t need them.Update: as noted in the comments, the separate bitmap heap applies to pre-Honeycomb versions of Android. As of Honeycomb, the bitmap heap was merged with the application heap. Here’s a SO post with more info.