On Android pre-honeycomb, Bitmaps have freaky memory issues because their data isn't stored in the VM. As a result it isn't tracked or removed by the GC. Instead it is removed when Bitmap.recycle()
is called (and that is also done automatically in the Bitmap
's finalizer).
This leads to some problems when doing image caching. When a bitmap is due to be evicted, I can't simply call recycle()
on it, because I have no idea if anyone else is using it.
My first thought was to do System.gc()
just before I load each bitmap. That way, hopefully orphaned Bitmap
s will be finalized and the native memory freed. But it doesn't work. Edit: Actually it does sort of work. I had my System.gc()
in the wrong place, after moving it, and halving my cache size (to what seems like a ridiculously small 2 MB of uncompressed bitmap data), my app no longer seems to crash (so far)!
My next thought was to implement manual reference counting, by subclassing Bitmap
and calling ReferenceCountedBitmap.decrementCount()
in all my activities' onDestroy()
methods. But I can't because Bitmap
is final.
I am now planning a BitmapManager
which keeps WeakReference
's to the bitmaps, and has methods like:
public void using(Bitmap bm);
public void free(Bitmap bm);
which count the references.
Does anyone have any experience or advice handling this? Before you suggest it, I can't ignore 80% of the market.