繁体   English   中英

如何在Android中释放位图内存

[英]how to release bitmap memory in android

在我们使用大量图像的程序中,我们取消了在eyery Activity和Fragment中的Drawables绑定,如下所示

protected void unbindDrawables(View view) {
    if (view != null) {
        if (view.getBackground() != null) {
            view.getBackground().setCallback(null);
        }
        if (view instanceof ImageView) {
            ImageView imageView = (ImageView) view;
            imageView.setImageDrawable(null);
        }
        if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
            if (!(view instanceof AbsSpinner) && !(view instanceof AbsListView)) {
                ((ViewGroup) view).removeAllViews();
            }
        }
    }
}

像这样https://stackoverflow.com/a/6779067所说,但是我用垫子发现位图也占用了很多内存而不释放。

Class Name                               |   Objects | Shallow Heap | Retained Heap

 android.graphics.Bitmap                 |       490 |       23,520 | >= 36,267,912
 android.graphics.Bitmap$1               |         1 |            8 |          >= 8
 android.graphics.Bitmap$2               |         0 |            0 |         >= 80
 android.graphics.Bitmap$BitmapFinalizer |       490 |        7,840 |      >= 7,840
 android.graphics.Bitmap$CompressFormat  |         3 |           72 |        >= 232
 android.graphics.Bitmap$CompressFormat[]|         1 |           24 |         >= 24
 android.graphics.Bitmap$Config          |         4 |           96 |        >= 360
 android.graphics.Bitmap$Config[]        |         2 |           72 |         >= 72
 android.graphics.BitmapFactory          |         0 |            0 |         >= 80
 android.graphics.BitmapFactory$Options  |         0 |            0 |              
 android.graphics.BitmapRegionDecoder    |         0 |            0 |         >= 48
 android.graphics.BitmapShader           |         9 |          216 |     >= 15,736
 Total: 12 entries (4,509 filtered)      |     1,000 |       31,848 |              

我不知道为什么不释放它,以及如何释放它,任何人都可以帮助我,非常感谢!

您必须调用bitmap.recycle()来释放在解码位图时分配的本机内存。

当然,您必须注意位图的生命周期。 要在适当的时候释放它。 更好的解决方案是使用某些图像加载器类来处理它。 参见https://github.com/nostra13/Android-Universal-Image-Loader

在位图上调用回收并删除对位图对象的任何引用

关键是,在蜂巢之前的Android版本中,位图的内存是从非托管内存分配的,这会造成各种问题。 它仍然是从位图对象实现的终结者发布的。 这意味着至少需要经过2次GC才能收集它。 同样,如果由于某种原因,终结器无法执行-您就知道了。 另一件事是-很难跟踪-DDMS看不到它,MAT也看不到。

对于Android 3.0,已进行了更改,并且在托管字节数组上实现了位图,但对于较旧的手机...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM