Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Out of Memory Exception / How does decodeResource add to the VM Budget?

I am pretty new to Android and have been developing a game. Every now and again I have users reporting out of memory exceptions, which I find surprising since the bitmaps that I create are at most 200 kb in size. I call BitmapFactory.decodeResource() whenever I create a new sprite. Since my application is a zombie defense game, you could expect that I create sprites quite often.

Every time I create a sprite, I call decode resource to generate a bitmap. My question is if I was to only call decode resource at the start of each activitiy, and refer to the bitmap at package level, would this lessen the amount of memory placed on the VM Budget?

like image 791
Emil Stewart Avatar asked Aug 14 '12 00:08

Emil Stewart


1 Answers

  • When you decode the Bitmap from an image resource like png, it depends more on the dimensions of image rather then the size in KBs.
  • Try if you can reduce the dimensions of original image without really impacting your output.
  • Try reusing the bitmaps rather then keep decoding them.
  • Explore more options with BitmapFactory.Options() object, for example increasing inSampleSize can reduce the amount of memory required by the image. e.g
    BitmapFactory.Options o=new BitmapFactory.Options();
    o.inSampleSize = 4;
    o.inDither=false;                     //Disable Dithering mode
    o.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared
    myBitMap=BitmapFactory.decodeResource(getResources(),ID, o);
    
  • One useful tricky solution if no other optimizations are really working out for you is that, you can catch the OutOfMemoryException and then can reduce the quality to max.. i.e. setting the inSampleSize to 16. It will reduce the quality of your images but at least will save your application from crashing, i did this in one of my app where I needed to load huge MP image in a bitmap.
like image 192
Umair Avatar answered Sep 28 '22 14:09

Umair