由绘制到位图引起的Android OOM

jjL*_*Lin 1 android bitmap

这是我的代码:

int[] image = {R.drawable.image1, R.drawable.image2, R.drawable.image1, R.drawable.image2,
        R.drawable.image1, R.drawable.image2, R.drawable.image1, R.drawable.image2,
        R.drawable.image1, R.drawable.image2, R.drawable.image1, R.drawable.image2,
        R.drawable.image1, R.drawable.image2, R.drawable.image1, R.drawable.image2,
        R.drawable.image1, R.drawable.image2, R.drawable.image1, R.drawable.image2,
        R.drawable.image1, R.drawable.image2, R.drawable.image1, R.drawable.image2};
Run Code Online (Sandbox Code Playgroud)

和getView:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {

        convertView=LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, null);
        ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView);
        imageView.setBackgroundResource(image[position]);

        return convertView;
    }
Run Code Online (Sandbox Code Playgroud)

一切都好.没有OOM.

然后,我想首先对drawable进行采样:

public static Bitmap sampleImage(Context context, int resourceId, int sampleSize) {        
            Bitmap resizeBmp = null;
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inSampleSize = sampleSize;
            resizeBmp = BitmapFactory.decodeResource(context.getResources(), resourceId, opts);

            return resizeBmp;
        }
Run Code Online (Sandbox Code Playgroud)

而新的getView:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {

        convertView=LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, null);
        ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView);
        Bitmap item = BitmapUtil.sampleMaskInShelf(getApplicationContext(), image[position], 4);
        imageView.setImageBitmap(item);
        //      imageView.setBackgroundResource(image[position]);

        return convertView;
    }  
Run Code Online (Sandbox Code Playgroud)

事情发生了.首先,应用程序不会崩溃.但是我使用的内存超过50MB,在我向上和向下滚动后,它会导致OOM.

问题是:1)为什么采样图像会增加使用的内存.2)如何减少使用的内存,还有其他方法吗?

Sco*_*t W 5

看来你在这里使用ListView?

在这种情况下,您可以通过以下几个步骤获得更好的服务(并希望节省大量内存):

  1. 您想尽可能尝试重复使用convertView.关于如何做到这一点,已经写了很多文章. 这是一个.
  2. 看起来你只有两个不同的图像(image1image2).看起来你每次getView()调用时都会对位图进行采样.您可能应该预先计算两个采样位图,然后一遍又一遍地使用这些位图.