7

I have an Activity which takes photos (with full possible resolution, so quite large), the application have then the chance to analyze them. Only one photo is handled at a time. The problem is that I run in to a "Out of memory" after 4 - 5 photos. I see

dalvikvm-heap Out of memory on a 5070745-byte allocation

(the byte size varies) followed by

Camera-JNI Couldn't allocate byte array for JPEG data

My application does not crash but as it appears to me the Camera simply becomes unable to deliver the images from this point on. I pay attention to memory usage in my application but here it seems that there is a memory leak somewhere outside and I'm asking me how can I cope with this. Any solution approaches existing for this?

georgij
  • 2,054
  • 4
  • 27
  • 43

2 Answers2

10

This may not be exactly what you are trying to do, but in order to display multiple large pictures (4-6 MB) on a grid view, I found this code to create a smaller bitmap with lower quality, to avoid out-of-memory situations:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 5;
options.inPurgeable = true;
options.inInputShareable = true;
Bitmap bm = BitmapFactory.decodeFile("/sdcard/myapp/" + filesFound.get(position), options);

The options are the important part, and by varying the settings, I managed to take memory down from where it would crash, to around 28MB when I started using the inSampleSize. It further went down with the inPurgeable and inInputShareable settings set to true. My activity is still sluggish, but it's much better.

For your application, if it can analyze a bitmap, the above code may shrink down the memory usage enough to make it work. I'm still new to Android, so it's possible this may not work at all.. ;-).

Regards,

Kevin

ktambascio
  • 434
  • 4
  • 17
3

Since you run out of memory after 4-5 pictures you probably arent calling yourBitmap.recycle(); after it has been saved to the SD-card?

Also in the onPictureTaken() method you could save the tempData from the picture into a bitmap using the Bitmap.Config.RGB_565 instead of ARGB(default) if you don't need the alpha channel.

   // Create options to help use less memory   
    Options opt = new Options();
    opt.inPreferredConfig = Bitmap.Config.RGB_565;

   // Decode the tempdata into a bitmap, with the options as the last argument 
    bitmapFromRawCameraTempData = BitmapFactory.decodeByteArray(rawCameraTempData, 0, rawCameraTempData.length, opt);
DecodeGnome
  • 1,809
  • 1
  • 19
  • 36
  • I used this, but It can not solve my memory problem? I also shouldn't use inSampleSize. What can I do more? – atasoyh Jun 28 '13 at 07:02
  • You could have a look at WeakReference, maybe it could help: https://weblogs.java.net/blog/2006/05/04/understanding-weak-references – DecodeGnome Jul 01 '13 at 11:48