$30 off During Our Annual Pro Sale. View details »

Drowning in Images — Memory Management

Drowning in Images — Memory Management

Outlines best-practices and problems encountered managing bitmaps in an Android application

Dallas Gutauckis

April 24, 2012
Tweet

More Decks by Dallas Gutauckis

Other Decks in Programming

Transcript

  1. dallasgutauckis DROWNING  IN  IMAGES   MEMORY  MANAGEMENT  

  2. github.com/dallasgutauckis Dallas  Gutauckis   dallas@gutauckis.com   h>p://dallasgutauckis.com   2  

  3. github.com/dallasgutauckis WHY  DO  I  NEED  TO   MANAGE  BITMAPS?  

    3  
  4. github.com/dallasgutauckis 4   FINITE  RESOURCES  

  5. github.com/dallasgutauckis TONS  OF  IMAGES   5  

  6. github.com/dallasgutauckis MEGAPIXELS   6   (Lots of pixels -- not

    really big ones)
  7. github.com/dallasgutauckis CONVINCED  YET?   7  

  8. github.com/dallasgutauckis SO.  IT  CRASHES   SOMETIMES…   8  

  9. github.com/dallasgutauckis AND  YOU  GET  NEGATIVE  FEEDBACK   9  

  10. github.com/dallasgutauckis WHAT  SHOULD  I  DO?   10  

  11. github.com/dallasgutauckis IT'S  OBVIOUS   11  

  12. github.com/dallasgutauckis DOWNVOTE  THE  REVIEW  AND   MARK  IT  AS  SPAM

      12  
  13. github.com/dallasgutauckis JUST  KIDDING   13  

  14. github.com/dallasgutauckis §  Use  a  download  manager   §  Don't  allow

     mulRple  concurrent  downloads  of  the  same  image   §  Don't  download  on  the  UI  thread   §  Lists  (GridView,  ListView,  AdapterView)   §  Avoid  downloading  images  while  flinging  (use  ScrollListener)   §  Cache!   §  Bitmaps  stored  naRvely  vs.  on  applicaRon  heap   §  LruCache<String,  Bitmap>  (Least-­‐recently  used)   §  Override  sizeOf(String,  Bitmap)   §  Override  entryRemoved(boolean,  K,  V,  V)   §  OutOfMemoryError   §  Evict!  Recycle!  Resize!   14  
  15. github.com/dallasgutauckis §  RESAMPLE   §  Save  memory  when  determining  resample

     factor,  just  decode  bounds     §  inSampleSize  to  tell  the  system  to  resample   §  Number  is  a  raRo  (1  pixel  for  every  X  original  pixels)   §  Factors  of  2  are  typically  more  performant   15  
  16. github.com/dallasgutauckis §  Avoid  the  ominous  "bitmap  is  recycled"  excepRon  

    §  Check  for  recycled  bitmaps   §  Bitmap#isRecycled();   §  ImageView#setImageBitmap(null);   §  Re-­‐download   16   RuntimeException: trying to use a recycled bitmap android.graphics.Bitmap
  17. github.com/dallasgutauckis §  Trying  to  draw  recycled  bitmaps   §  Determining

     the  size  of  a  Bitmap  by  decoding  the  enRre  Bitmap   §  Downloading  items  that  may  never  be  visible   §  LruCache  is  thread-­‐safe.  Synchronize!   17  
  18. github.com/dallasgutauckis §  I/O  Memory  Management  Talk   h>p://www.youtube.com/watch?v=_CruQY55HOk   § 

    Displaying  Bitmaps  Efficiently   h>p://developer.android.com/training/displaying-­‐bitmaps/index.html   18