So far, I have not found a reliable way to cope with image size and available memory. The problem is that memory is fragmented very quickly, so you may have 10 MB of free space, but there is no contiguous space for a 2 MB image. What is really needed is the size of the largest free space, but there seems to be no way to get this. A better way would be to defragment the memory, but there is no such function for this.
However, if your available memory is smaller than the image, you can be sure that you would run into it if you tried to use it, so it has some advantages to at least check before using it.
With tablets at the end of 2012 having a resolution of 1920x1280, we need 20 MB of continuous memory for one background image! It looks like some of these tablets now allow heaps of up to 256 MB, but throwing more VM space seems to solve it, we really need a memory defragmenter or a way to reserve space.
There is one trick that can help if the image size is not scaled or resized, and each resized image has the same size. And you are limiting your Android 3.0+ application:
Options opt2 = new BitmapFactory.Options(); opt2.inBitmap = mBitmap; // reuse mBitmap to reduce out of memory errors mBitmap = BitmapFactory.decodeResource(getResources(), myDrawable, opt2);
This will allow you to reuse the same mBitmap memory area for the image.
Frank
source share