1

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.

Community
  • 1
  • 1
lujop
  • 13,504
  • 9
  • 62
  • 95

1 Answers1

0

A Drawable is much more broad than a Bitmap. Drawable is intended to represent anything the graphics system can render to the display. There are subclasses of Drawable - such as as ShapeDrawable, or ColorDrawable - that do not contain Bitmaps and hence do not need any sort of manual memory management.

A BitmapDrawable wraps a Bitmap and contains a reference to a Bitmap. The Bitmap is special, because Android maintains the pixel data for all Bitmaps in a separate heap, which is managed separately from the rest of your application. When the Android garbage collector cleans up a Bitmap object, it also cleans up the the pixel data from the bitmap heap. But you can force it to happen sooner by manually calling recycle() on the Bitmap, which marks the Bitmap invalid 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.

Community
  • 1
  • 1
mportuesisf
  • 5,587
  • 2
  • 33
  • 26
  • Then if I understood correctly there's any "magic". And if I manually create a Bitmap and set on Imageview after onCreateView I can expect that Android will release it in the same way it releases the ones created by image resources? – lujop Aug 06 '12 at 19:00
  • 1
    As long as your Activity isn't holding any references to the manually created Bitmap (for instance, in a static field or something), it will get cleaned up by the garbage collector along with all the rest of the View objects. The recycle() method is useful if you know you won't need the bitmap anymore, and want to free up the bitmap heap for something else. – mportuesisf Aug 06 '12 at 19:04
  • This is although pre-honeycomb, since honeycomb the bitmap memory is in the same heap as the rest of the app. – User Aug 06 '12 at 19:09
  • @lxx - I was dimly aware of that change; thanks for the correction. – mportuesisf Aug 06 '12 at 20:05