2

How exactly does image recycling work in Android?

Allow me to elaborate:

If I have the following:

myBitmap = BitmapFactory.decodeResource(curView.getResources(), R.drawable.mypic);

And log the following

Log.v("ImageStuff","Image is: "+myBitmap);

I get the following result:

Image is: android.graphics.Bitmap@(ResourceID here)

Which is great, however if I do the same thing but call a recycle like so

myBitmap = BitmapFactory.decodeResource(curView.getResources(), R.drawable.mypic);
myBitmap.recycle()

I get the same results as above. I thought that calling recycle would clear the bitmap so it would log as null?

Also if I have a method that takes a bitmap like so:

public void doStuff(Bitmap pic){

//Code here

}

Create my bitmap as above and send it through to doStuff:

myBitmap = BitmapFactory.decodeResource(curView.getResources(), R.drawable.mypic);
doStuff(myBitmap);

If I want to recycle the image, would I need to call myBitmap.recycle(); as well as pic.recycle (within my doStuff method after I'd finishing with it).?

Zippy
  • 3,826
  • 5
  • 43
  • 96

2 Answers2

1

Bitmap object contains image data (pixel values allocated under the hood), it is not itself the image data. So, Bitmap object can hang around after recycle(), but will throw error when you try to work with data.

You call recycle() when you, or any other object, is no longer going to use Bitmap in any way. You can also set myBitmap = null to have the object itself garbage collected.

S.D.
  • 29,290
  • 3
  • 79
  • 130
  • Thanks @User117 So it's just a pointer to the image data? This being the case, would I need to only recycle one of the two instances that I have pointing back to the same image and if so which one? Or does it not matter? Or should I call recycle on both? (as in my example above) – Zippy Mar 04 '13 at 15:06
  • @Zippy Yes, as both variables point to same Object, calling `recycle()` on any of the variable's will invoke `recycle()` on that Bitmap Object. – S.D. Mar 04 '13 at 15:08
1

To expand upon User117's comments:

1) A Bitmap is just a container for the image data. When you call recycle, it removes all the image data, but still keeps the container.

2) If you pass the Bitmap into your doStuff method that just pass a reference to the bitmap, there is no need to call recycle twice as the objects are the same. Just call recycle on myBitmap after your call to doStuff if you no longer need it.

Justin Breitfeller
  • 13,737
  • 4
  • 39
  • 47