Android: How Does Bitmap Recycle() Work?
Answer :
The first bitmap is not garbage collected when you decode the second one. Garbage Collector will do it later whenever it decides. If you want to free memory ASAP you should call recycle()
just before decoding the second bitmap.
If you want to load really big image you should resample it. Here's an example: Strange out of memory issue while loading an image to a Bitmap object.
I think the problem is this: On pre-Honeycomb versions of Android, the actual raw bitmap data is not stored in VM memory but in native memory instead. This native memory is freed when the corresponding java Bitmap
object is GC'd.
However, when you run out of native memory, the dalvik GC isn't triggered, so it is possible that your app uses very little of the java memory, so the dalvik GC is never invoked, yet it uses tons of native memory for bitmaps which eventually causes an OOM error.
At least that's my guess. Thankfully in Honeycomb and later, all bitmap data is stored in the VM so you shouldn't have to use recycle()
at all. But for the millions of 2.3 users (fragmentation shakes fist), you should use recycle()
wherever possible (a massive hassle). Or alternatively you may be able to invoke the GC instead.
You will need to call myBitmap.recycle() before loading the next image.
Depending on the source of your myFile (E.g. if it is something you have no control over the original size), when loading an image instead of just simply resampling some arbitrary number, you should scale the image to the display size.
if (myBitmap != null) { myBitmap.recycle(); myBitmap = null; } Bitmap original = BitmapFactory.decodeFile(myFile); myBitmap = Bitmap.createScaledBitmap(original, displayWidth, displayHeight, true); if (original != myBitmap) original.recycle(); original = null;
I cache the displayWidth & displayHeight in a static that I initialized at the start of my Activity.
Display display = getWindowManager().getDefaultDisplay(); displayWidth = display.getWidth(); displayHeight = display.getHeight();
Comments
Post a Comment