Android – How to effectively recycle a Bitmap which is created as per below code

androidbitmaprecycle

I have created Bitmap like below,

// create bitmap in the below line
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.googlelogo320x480);

And I have set it to an ImageView.

my questions are:
1> Do I need to explicitly call Bitmap.recycle() on the above Bitmap?
2> If yes then when should I call it? I have tried calling it immediately after the 3rd line i.e, after setting the bitmap to an ImageView, however I get an exception that Canvas trying to draw a recycled Object.
3> Is it going to be a memory leak if recycle() is never called on the Bitmap in my code?
P.S: I am working on ICS or above.

Best Answer

In this particular case, no, you shouldn't call recycle(); the ImageView will call recycle() when it is done with it. This has been true for a while, ICS did nothing to change this fact.

You need to call recycle() when your code is done with the image. For example if you were applying 10 filters to one image and generating a new Bitmap on each step, you SHOULD call recycle() on the old Bitmap after each step.

That said, you can't have an unlimited number of Bitmaps at the same time, especially large ones. That's when you need to be clever and load/unload dynamically.

Related Topic