I have to free memory occupied by bitmaps. So I’m calling recycle() on all of them, when my activities finish.
These bitmaps are always used in drawables, either as background property or source (case of ImageView) property.
But the problem is, when later another activity has a view that also uses these bitmaps, it will show
java.lang.RuntimeException: Canvas: trying to use a recycled bitmap.
What can I do, I can’t keep the bitmaps in memory only because maybe the user starts, at some point later, an activity which uses them. How do I tell the bitmaps to free memory and also please be possible to be used later again?
The solutionis to initialize the Bitmap and View using this:
This does not work for XML bitmaps although. But the bitmap should be retrievable from the view.
Having the bitmap instance in memory, it’s possible to call recycle() on it to free memory immediatly.
And before recycling the bitmap it has to be ensured that it’s not referenced by any view anymore – setting the references of the drawable / view to null. Otherwise the exception will be thrown. In order to do this it’s necessary to keep track of the views which are referencing a bitmap and null all the references before recycling it.
So my actual problem was not reusing the bitmap. The problem was recycling the bitmap while is still referenced by a view.