Android 在使用Bitmap的时候为啥要手动调用recycle方法呢?
来源:互联网 发布:矩阵秩为1和迹的关系 编辑:程序博客网 时间:2024/06/05 07:18
我们知道手机的内存有限,而图片所占的内存往往又很大。所以在处理图片的时候可以在服务端或者客户端提前将图片处理一下,减少其体积。另外使用Bitmap的时候可以使用SoftReference来及时释放资源。但是看到好多程序还是主动地调用Bitmap对象的recycle方法来释放资源。可能我们就有疑问了:不是java会自动回收内存吗,那干吗还要手动地去回收?
要解决这个问题,我们得去看看recycle的源码:
/** * 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. */ public void recycle() { if (!mRecycled) { if (nativeRecycle(mNativeBitmap)) { // return value indicates whether native pixel object was actually recycled. // false indicates that it is still in use at the native level and these // objects should not be collected now. They will be collected later when the // Bitmap itself is collected. mBuffer = null; mNinePatchChunk = null; } mRecycled = true; } }
通过看源码,我们会发现,这个方法首先将这个Bitmap的引用置为null,然后调用了nativeRecycle(mNativeBitMap)方法,这个方法很明显是个JNI调用,会调用底层的c或者c++代码就可以做到对该内存的立即回收,而不需要等待那不确定啥时候会执行的GC来回收了。
当然如果用的图片很少,占用的内存也很少的时候就没有必要手动调用recycle方法来回收内存了,GC会在合适的时候回收这些内存的。只有图片很多占用内存很多的时候才需要我们主动调用recycle方法,否则很有可能出现OOM异常的。
0 0
- Android 在使用Bitmap的时候为啥要手动调用recycle方法呢?
- Android 在使用Bitmap的时候为啥要手动调用recycle方法呢?
- Android系统中Bitmap是否有调用recycle方法的必要性?
- Android系统中Bitmap是否有调用recycle方法的必要性
- Android系统中Bitmap是否有调用recycle方法的必要性? .
- Android系统中Bitmap是否有调用recycle方法的必要性
- Android系统中Bitmap是否有调用recycle方法的必要性?
- Android系统中Bitmap是否有调用recycle方法的必要性
- Android系统中Bitmap是否有调用recycle方法的必要性
- Android系统中Bitmap是否有调用recycle方法的必要性
- 是否需要主动调用Bitmap的recycle方法?
- Bitmap为什么要调用recycle()方法来显示释放内存
- Android中有没有必要调用Bitmap的recycle()
- android Bitmap.recycle()的相关问题
- Android Bitmap使用recycle()后 报:trying to use recycled bitmap 的问题
- Bitmap recycle方法与制作Bitmap的内存缓存
- Bitmap recycle方法与制作Bitmap的内存缓存
- Bitmap recycle方法与制作Bitmap的内存缓存
- oracle 分组编号 ROW_NUMBER() OVER(PARTITION BY COLUMN ORDER BY COLUMN ) 的用法
- Swift代替OC中[AnyObject Class]的语句
- 头部搜索input【网页制作】
- iOS 将服务器下载下来的db文件和本地的db文件合并后保存
- 【BZOJ1565】[NOI2009]植物大战僵尸【最大权闭合图】【拓扑排序】
- Android 在使用Bitmap的时候为啥要手动调用recycle方法呢?
- SpringMVC——最小化配置
- fir.im Weekly - Stanford 的 Swift 课程来了
- Restfu架构设计l概述
- MVX Android设计架构浅析-MVVM
- c++判断文件夹是否存在,若不存在,调用linux命令创建它
- HDU 1028 Ignatius and the Princess III(整数拆分问题)
- 一个HTTP Servlet处理POST方式的例子
- MVX Android设计架构浅析-MVP