android - OutOfMemory when loading large Background Image -


i using android:background give background image android layout.
after putting images exception :

08-24 00:40:19.237: e/dalvikvm-heap(8533): out of memory on 36000016-byte allocation. 


how can use large images backgrounds on android?
can expand application heap memory? or not ?

please have @ related question:

high resolution image - outofmemoryerror

try minimize memory usage of application keeping background image small possible.

this can done via:

  • cropping image fits screen
  • compress image further (use e.g. photoshop) before using in app
  • use below method load bitmap
  • recycle bitmap no loger need it
  • make sure not keep multiple instances of in memory
  • set reference null after using bitmap

make sure images set background loaded (e.g. cropped in size, example fit screen size) , released memory no longer needed.

make sure have 1 instance of bitmap in memory. after displaying it, call recycle() , set reference null.

this how load images:

public static bitmap decodesampledbitmapfromresource(resources res, int resid,         int reqwidth, int reqheight) {      // first decode injustdecodebounds=true check dimensions     final bitmapfactory.options options = new bitmapfactory.options();     options.injustdecodebounds = true;     bitmapfactory.decoderesource(res, resid, options);      // calculate insamplesize     options.insamplesize = calculateinsamplesize(options, reqwidth, reqheight);      // decode bitmap insamplesize set     options.injustdecodebounds = false;     return bitmapfactory.decoderesource(res, resid, options); }  public static int calculateinsamplesize(             bitmapfactory.options options, int reqwidth, int reqheight) {     // raw height , width of image     final int height = options.outheight;     final int width = options.outwidth;     int insamplesize = 1;      if (height > reqheight || width > reqwidth) {          // calculate ratios of height , width requested height , width         final int heightratio = math.round((float) height / (float) reqheight);         final int widthratio = math.round((float) width / (float) reqwidth);          // choose smallest ratio insamplesize value, guarantee         // final image both dimensions larger or equal         // requested height , width.         insamplesize = heightratio < widthratio ? heightratio : widthratio;     }      return insamplesize; } 

thanks adam stelmaszczyk beautiful piece of code.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -