I have in my application many bitmaps. They are loaded when application start. In one activity I have a two buttons where I change language, but when I click on button I start loading images again. Sometimes I get error with out of memory. How I can clean memory, that when I click on button I clean memory and after that loading bitmaps? This is possible to do? Now I use system.exit(0) but I don’t want close all application.
I have in my application many bitmaps. They are loaded when application start. In
Share
I was facing the same issue with a graphics-processing intensive app a while ago and after lots of debugging I figured out that Bitmap objects are not properly freed automatically.
You should manage Bitmaps on your own by calling their recycle method as soon as you don’t need them anymore (Activity.onStop method for example).
EDIT (10/08/2014):
The Android developer documentation finally contains clear explanations for these bitmap memory problems. Some things have changed in the meanwhile for the better, but we typically still have to deal with older Android versions that make bitmap memory management difficult.
Here are the key points:
As of Android 2.3.3 (API level 10) and lower
The problem shows up when you already depleted the Dalvik heap memory limit with bitmaps (or other big objects) and try to load another bitmap. Even if you do not hold any references anymore on older bitmap objects, it is not guaranteed that those bitmaps get garbage collected before a new bitmap object is allocated. Therefore you can randomly hit the limit and get an
OutOfMemoryError.It is therefore important to manage bitmap objects yourself. When you are done with using a bitmap you should call its
recycle()method before loading another bitmap.Since Android 3.0 (API level 11)
Here Dalvik’s memory manager can see how much memory is left and has full control over reclaiming memory.
Managing Bitmaps
In both cases (older Android versions and newer) you may want to manage your bitmap objects in order to avoid:
The Android developer documentation contains detailed information about how to cache and reuse already loaded bitmap objects using a least-recently-used cache (LruCache).