Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Not calling recycle() will not cause memory leak, but it may cause your app to go over the memory limit and explode, see below to see whether your app qualify:

  1. If you are only interested in ICS and above, you shouldn't need to worry about calling recycle(), as a Bitmap's actual backing data is stored in Dalvik controlled memory. Therefore as long as you don't keep a reference to a Bitmap around, Dalvk should be able to GC it with no problem.
  2. Even if you wish to support Android 2.3 or prior, Bitmaps will eventually be released, so if your app is not Bitmap intensive, you shouldn't need to worry about it either.
  3. BUT, if you are supporting Android 2.3 or prior, and use lots of Bitmaps, then you should recycle a Bitmap as soon as it is done.

try this

if (myBitmap != null) {
    myBitmap.recycle();
    myBitmap = null;
}
Bitmap original = BitmapFactory.decodeFile(myFile);
myBitmap = Bitmap.createScaledBitmap(original, displayWidth, displayHeight, true);
original.recycle();
original = null;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top