Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How does Bitmap recycle() work?

Tags:

android

bitmap

Let's say I have loaded an image in a bitmap object like

Bitmap myBitmap = BitmapFactory.decodeFile(myFile); 

Now, what will happen if I load another bitmap like

myBitmap = BitmapFactory.decodeFile(myFile2); 

What happens to the first myBitmap? Does it get Garbage Collected or do I have to manually garbage collect it before loading another bitmap, eg. myBitmap.recycle()?

Also, is there a better way to load large images and display them one after another while recycling on the way?

like image 668
Anuj Tenani Avatar asked Sep 29 '10 16:09

Anuj Tenani


People also ask

Is bitmap recycle necessary?

It is not necessary, but is highly recommended! It will speed up the memory freeing process and will save you of torture with Out Of Memory exception. I would say its mandatory if you are going to do any serious an memory extensive work with Bitmaps.

How do I know if my Android BMP is empty?

You can do a check when you want to return the BitMap look to see if the ArrayList of Paths is bigger than 0 and return the BitMap if so, or else return null.

How do you handle bitmaps in Android as it takes too much memory?

Choose the most appropriate decode method based on your image data source. These methods attempt to allocate memory for the constructed bitmap and therefore can easily result in an OutOfMemory exception. Each type of decode method has additional signatures that let you specify decoding options via the BitmapFactory.


1 Answers

The first bitmap is not garbage collected when you decode the second one. Garbage Collector will do it later whenever it decides. If you want to free memory ASAP you should call recycle() just before decoding the second bitmap.

If you want to load really big image you should resample it. Here's an example: Strange out of memory issue while loading an image to a Bitmap object.

like image 150
Fedor Avatar answered Sep 22 '22 12:09

Fedor