Question

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).?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top