Android位图内存泄漏

Android位图内存泄漏

本文介绍了Android位图内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Android创建缓存的图像系统,但是内存消耗却越来越大.我通过Android 网站查看了一些想法,但问题仅仅是不想消失.

I am trying to create cached image system for Android but the memory consumption just grows and grows. I looked through Android website for some ideas, but the issue just doesn't want to disappear.

以下是我从SD卡获取图像,对其进行设置并随后销毁的代码.我在做什么错了?

Below is my code of getting the image from SD card, setting it and later destroying.What am I doing wrong?

WeakReference<Bitmap> newImageRef;
    public void setImageFromFile(File source){
        if(source.exists()){

            Bitmap newImage = BitmapFactory.decodeFile(source.getAbsolutePath());
            newImageRef =   new WeakReference<Bitmap>(newImage);
            if(newImage != null){
                this.setImageBitmap(newImage);
            }
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        Bitmap newImage = newImageRef.get();
        if (newImage != null) {
        newImage.recycle();
        newImage = null;
        }


        Drawable drawable = getDrawable();
        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            Bitmap bitmap = bitmapDrawable.getBitmap();
            if (bitmap != null){
            bitmap.recycle();
            }
        }
        this.setImageResource(0);
        newImage = null;
        newImageRef = null;
        System.gc();


        super.onDetachedFromWindow();
    }

推荐答案

如果您使用的是Android版本> 3.0,则不必调用recycle(),因为只要没有,gc最终都会自行清理位图.引用它.因此,删除回收呼叫是安全的.他们在这里什么也没做.

If you are using Android version >3.0 you dont have to call recycle()as the gc will clean up bitmaps on its own eventually as long as there are no references to it. So it is safe to remove recycle calls. They do nothing much here.

您发布的代码看起来很整洁,但是您确定那里的泄漏不是在其他地方发生的.使用Android Memory Analyzer工具查看泄漏发生的位置,然后发布信息.

The code which you posted looks neat but are you sure there the leak is not happening somewhere else. Use Android Memory Analyzer tool to see where the leak is happening and then post the info.

祝你好运.

这篇关于Android位图内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 05:10