You cannot "clear the heap." the virtual machine will do this automatically when your objects are no longer referenced.
As they say, bitmaps are a tough thing in Android. There is limited memory, and when an image is decoded into a bitmap image, it can take up much more memory than the compressed image format itself.
There is no simple answer to your decision. Even if you do it right, you can just run out of memory. That being said, here are some tips:
Use Bitmap.release()
. Bitmap images are special in that they are allocated in the heap of the original stack (unlike VM). Javadocs are a bit fuzzy, saying you usually don't need to call this, but, in my experience, this βhintβ for the virtual machine that you made with memory support is important. EDIT: with Android 3.0 (API level 11), pixel data is stored in the Dalvik heap along with the corresponding bitmap.
Loading raster images into memory is scalable. Here 's a blog post on this topic. You only get a bunch of 24 MB on some devices, and a high-resolution image can exhaust all this when loaded into a raster object. There is no way around this, so you should load it scaled.
Do not call System.gc()
as another answer said. The people who built the GC algorithm are smarter than you and me; They know what they are doing. You will never get OOME when there is memory that can be freed via the GC - GC will always work until OOME is provided.
This is obvious, but make sure you don't keep links to bitmaps when they are no longer needed.
Finally, and it sucks, Android does not perform heap compaction. Here's the SO Question , which I posted on it some time ago, without a satisfactory answer. In a nutshell, Android never squeezes a bunch, since your application continues to allocate large or even medium sizes, pieces for bitmap images, you will end up in a situation where, while you are not out of memory, there is not enough large adjacent piece of memory for your distribution and you get OOME. The only way around this, as I wrote in my question, is to kill the application process when the user shuts down. This will make the launch slower next time, but guarantee a new heap. Do not get me wrong, I canβt believe that this is the right thing, but no one came up with a better solution.
source share