Nov 14, 2011

How to Solve OutOfMemory Error (OOM) in Android ?

When you try to decode large files on your Android device (where you have only 16MB memory available) you wil surely get an OutOfMemory exception.

We have found that if you create a temp storage and pass it to BitmapFactory before decoding might help.

So, before using BitmapFactory.decodeFile() create a byte array of 16kb and pass it to temp storage in decoding process.

BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];

Bitmap bitmapImage = BitmapFactory.decodeFile(path,opt);

Also you might consider passing your own outputstream that streams out to server or other storage to minimize memory consumtion during the process.

PS, do not forget to bitmapImage.recycle() after usage.

Also consider using options.inSampleSize with values other than 1. From SDK: If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. (1 -> decodes full size; 2 -> decodes 1/4th size; 4 -> decode 1/16th size). Because you rarely need to show and have full size bitmap images on your phone. For manipulations smaller sizes are usually enough.

No comments:

Post a Comment