使用后(在Android中)是否需要调用Bitmap.recycle()? [英] Is it needed to call Bitmap.recycle() after used (in Android)?

查看:22
本文介绍了使用后(在Android中)是否需要调用Bitmap.recycle()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Bitmap.recycle()的Android参考文档:

According to Android Reference Document of Bitmap.recycle():

释放与此位图关联的本机对象,并清除参考像素数据.这不会释放像素数据同步;它只是允许它被垃圾收集,如果有的话没有其他参考.位图被标记为死",意味着它如果调用 getPixels() 或 setPixels() 将抛出异常,并且什么也不会画.此操作不可逆转,因此应仅在您确定没有其他用途时才调用位图.这是一个高级调用,一般不需要调用,因为正常的 GC 进程会在没有内存时释放这块内存对此位图的更多引用.

Free the native object associated with this bitmap, and clear the reference to the pixel data. This will not free the pixel data synchronously; it simply allows it to be garbage collected if there are no other references. The bitmap is marked as "dead", meaning it will throw an exception if getPixels() or setPixels() is called, and will draw nothing. This operation cannot be reversed, so it should only be called if you are sure there are no further uses for the bitmap. This is an advanced call, and normally need not be called, since the normal GC process will free up this memory when there are no more references to this bitmap.

但是,我读过的许多书都建议通过调用 Bitmap.recycle() 一次以确保不再需要它来释放内存.

But, many books I read suggest to free memory by calling Bitmap.recycle() once make sure no longer need it.

搞糊涂了:用完需要调用Bitmap.recycle()吗?

It make me confused: Is it needed to call Bitmap.recycle() after used?

推荐答案

视情况而定.

如果您在 Android 3.0 及更高版本上运行您的应用,则不需要它,因为 GC 会完美地处理它.

If you run your app on Android 3.0 and above, it's not needed as the GC will take care of it perfectly.

但是,如果您在旧版本上运行您的应用程序,由于位图不会被 GC 很好地监控(它认为它们是参考的大小),您可能会出现 OOM,如 Google IO 讲座中所示 此处.

However, if you run your app on older versions, since bitmaps don't get monitored well by the GC (it thinks they are the size of a reference), you could get OOM, as shown on Google IO lecture here.

无论如何,仍然建议您在确定不再需要位图后立即调用 recycle.即使对于新的 android 版本也很好,因为它降低了自动内存管理所需的工作......

In any case, it's still recommended to call recycle as soon as you are sure you don't need the bitmap anymore. It's good even for new android versions, since it lowers the work needed for automatic memory management...

其实我记得我问过一个类似的问题 这里.

In fact, I remember I've asked a similar question here.

此外,如果您需要使用 JNI 对位图进行额外控制,请查看 这篇文章.

Also, if you need extra control of bitmaps using JNI, check out this post.

所以,简而言之,答案是不再需要它,但仍然推荐它.

So, in short, the answer is that it's not needed anymore, but still recommended.

自 Android 8.0 以来,位图存储在本机内存中,因此更难达到 OOM.事实上,这在技术上是不可能的,因为你会遇到其他问题.可以在此处找到有关这方面的更多信息.

Ever since Android 8.0, Bitmaps are stored in native memory, so it's harder to reach OOM. In fact, it's technically impossible, as you will get into other issues instead. More information about this can be found here.

这篇关于使用后(在Android中)是否需要调用Bitmap.recycle()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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