Android setBackgroundResource cause out of memory excepiton

好久不见. 提交于 2019-11-27 07:07:36
TheModularMind

I solved! All your hints were good but the real problem was the "/drawable" folder! I had all the pictures in "/drawable" generic folder that is considered by the system like "/drawable/mdpi", so when I were running in devices with hdpi or more the images were resized, and became too big which cause OutOfMemoryException!

Now i'm using "/drawable-nodpi" to store my images. This folder works like "/drawable" but the images are never resized!

Each Android application has limited memory (heap) which can be used by Dalvik VM. It is 32 MB on some devices it is 64 MB. When you set background resource you load that resource on heap. That resource is loaded as Bitmap - it's size is width * height * pixel size. Usualy Bitmaps are loaded as ARGB images which has 4 bytes per pixel. It means that loading 1024x768 image takes 1024*768*4 = 3145728 B = 3072 kB = 3 MB on heap. When you load lot of large images it consumes all free heap memory and causes out of memory exception.

To fix this it is better to load images as small as you can - when you are displaying thumbnail of image it is sufficient to load it in resolution which is not much larger than is resolution of concrete part of display. It means that when you display your image on 800x600 display it is not sufficient to load 1024x768 image. You can use BitmapFactory to load image in smaller resolution.

Use method decodeResource(activity.getResources(), R.drawable.imageId, opts). BitmapFactory.Options opts has parameter inSampleSize where you can set subsampling of image. Also parameter inPreferredConfig can be used to set RGB_565 instead of ARGB_8888 in case when you don't need transparency.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!