I'm currently working on an embedded device using Android 2.3.3 with very few memory. The GUI is using lot of bitmaps, and sometimes, we saw some OutOfMemory exceptions due to Android not handling the bitmap memory well enough to free the memory fast enough for a new activity to start correctly.
To be exact, Android official documentation ( https://developer.android.com/training/displaying-bitmaps/manage-memory.html ) tells us :
On Android 2.3.3 (API level 10) and lower, the backing pixel data for a bitmap is stored in native memory. It is separate from the bitmap itself, which is stored in the Dalvik heap. The pixel data in native memory is not released in a predictable manner, potentially causing an application to briefly exceed its memory limits and crash.
In Android 2.3.3 (API level 10) and lower, using recycle() is recommended. If you're displaying large amounts of bitmap data in your app, you're likely to run into OutOfMemoryError errors. The recycle() method allows an app to reclaim memory as soon as possible.
Caution: You should use recycle() only when you are sure that the bitmap is no longer being used. If you call recycle() and later attempt to draw the bitmap, you will get the error: "Canvas: trying to use a recycled bitmap".
So I started to implement some recycle() in onDestroy() but I'm facing different issues :
-onDestroy() is not reliable, since we can't be sure Android will call it before fully kill the application. So, even if it seems to be the good place to clean bitmaps, it may happen that an activity is instantly killed while another starts and can't allocated memory for its own bitmaps.
- Would there be a better place to implement the recycling of bitmaps?
-Some drawables are declared through Java code, those are easy to recycle since we can keep a reference to them. But what about the ones declared through Xml?
- Is there a way to find all BitmapDrawable of a view (without looking the full view tree)?
- How Android is managing XML-declared drawable? Is there only one java object / xml object? (meaning you could have some issues if a xml reference is used in several views/activities) Having only one instance of each object would greatly reduce the memory used but would requires much more logic to be clean properly.
Those specific questions lead to the main issue : How to handle bitmaps to be sure that before another onCreate(), we cleaned every bitmap of the previous activity?
Thanks!
you can use finalize() method for perform certain tasks.
This way,you can double check that memory is released.
example
Another way
Another way of implementation is by downsampling and caching of bitmaps. If caching is efficient,then you can assisn and release bitmaps on onstart() and onStop() methods.So you can release memory as soon as the activity is out of focus.