I am working on an app having a lot of image and using a sensor listener that I register at the beginning of the activity with the sensor manager to detect shake events and change images based on shake direction.
I read the event values in onSensorChanged(SensorEvent event) in order to use it in my app:
public void onSensorChanged(SensorEvent event){
accX = event.values[0];
accY = event.values[1];
accY = event.values[2];
}
I unregister the sensor listener on pause of the activity and also call system.gc for garbage collection.
Everything works well till I am on a single activity.
When I finish current activity and open another activity (again having a a sensor listener), app starts giving out of memory exception after a while:
“OutOfMemoryException: bitmap size
exceeds VM budget”
Note that heap size of the app is never more than 4 MB.
One more observation is that the app never crashes if sensor listener is not used which makes me thinks that possibly there are memory leaks when sensor events are generated and when a new activity is loaded, due to lesser memory available, the app gives OutOfMemoryException when bitmaps are used in the activity.
So seemingly two possible reasons:
- images are not recycled properly
http://code.google.com/p/android/issues/detail?id=8488 - every time there is a SensorEvent, somewhere there are memory leaks which decreases the available memory for an app
Android: reading accelerometer without memory allocation?
I’m also using the solution described in comment 51 here:
http://code.google.com/p/android/issues/detail?id=8488
to recycle everything but it still gives memory issues.
If you can tell me the best approach to use the images in a large size app, how to recycle them and confirm if there are really any memory leaks while using the sensor listener, or any suggestions what I should look for in the app, it will be really helpful.
For the images to get recycled properly, if possible, try using Bitmap.recycle() method. This is becasue the image is actually kept as a reference (in pre-Honeycomb) and the actual data is allocated using native memory.
In Honeycomb the memory for images is allocated on the heap so it is easilly GCed. Additionally, you may set largeHeap=”true” (again post-Honeycomb).