Android - 位图和内存管理? [英] Android - Bitmap and memory management?

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

问题描述

我在很多示例中看​​到,开发人员在位图上调用recycle(),然后将其设置为null.为什么这是必要的,垃圾收集器不负责释放位图吗?

I've seen in a lot of samples, that developers call recycle() on bitmap, and then set it to null. Why is this necessary, doesn't the garbage collector take care of releasing the bitmap?

Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
bitmap.recycle();
bitmap = null;

推荐答案

加入俱乐部.它有点像但不完全是.

Join the club. It kind of does but not quite.

问题是,在 Android 的蜂窝前版本中,位图的内存是从非托管内存分配的,这会产生各种各样的问题.它仍然被释放,但来自位图对象实现的终结器.这意味着至少需要 2 次 GC 才能收集它.此外,如果由于某种原因终结器无法执行 - 你得到了图片.另一件事是 - 真的很难追踪 - DDMS 没有看到它,MAT 也没有

The thing is that in the pre-Honeycomb versions of Android the memory for bitmaps was (is) allocated from unmanaged memory, which creates all sorts of problems. It is still released but from the finalizer of the bitmap object implementation. Which means that it will take at least 2 passes of GC to collect it. Also if for whatever reason the finalizer fails to execute - you got the picture. Another thing is - it is really difficult to trace - DDMS does not see it and neither does MAT

对于 Android 3.0,这一点已经改变,位图是通过托管字节数组实现的,但对于较旧的手机...

For Android 3.0 this has been changed and bitmaps are implemented over managed byte arrays, but for the older phones...

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆