android中Bitmap数据如何释放
2014-03-19 18:24
204 查看
今天来研究一下android中的Bitmap。在实际开发中,Bitmap经常用到,特别是游戏开发。可以说游戏开发其实就是对图片(Bitmap)操作!可见Bitmap有多重要。这里我们主要讨论的是Bitmap资源释放原理。 我们知道,用完一个Bitmap后,需要马上recycle()来保证尽快释放期资源。首先,我们来看看recycle()这个函数的定义(Bitmap.java):
这个时候finalize()就登场了。我们先看看里面定义的一个私有变量private final BitmapFinalizer mFinalizer; BitmapFinalizer 是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; } }代码很简单,主要调用这个函数:nativeRecycle(mNativeBitmap)去释放。这里是JNI方式去调用了c写的方法!其实,你看看一下Bitmap这个类,就知道了,其实Bitmap的实现主要都是用C写的,为了保证效率这样选择是必然的! 这不是我们讨论的重点。我们来看看google给这个函数的一段说明:
/** * 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. */通过这段说明我们知道调用这个函数其实只是会free一些相关的资源、对于其t图片像素数据并没有同步释放,而且这个方法通常也不是必要的,就是说:不是一定要调用这个函数这个Bitmap才会被GC回收。那么问题就来了:刚才说了,那图片像素这类数据是如何释放的呢?最重要的是bitmap处理的核心代码不是JAVA写的。
这个时候finalize()就登场了。我们先看看里面定义的一个私有变量private final BitmapFinalizer mFinalizer; BitmapFinalizer 是Bitmap的内部类:
private static class BitmapFinalizer { private final int mNativeBitmap; BitmapFinalizer(int nativeBitmap) { mNativeBitmap = nativeBitmap; } @Override public void finalize() { try { super.finalize(); } catch (Throwable t) { // Ignore } finally { nativeDestructor(mNativeBitmap); } } }这里很好的利用object的finalize()这个回调函数,这样就来保证一个Bitmap对象被释放的时候能够回调void nativeDestructor(int nativeBitmap);这个函数来释放C里面申请的资源!
相关文章推荐
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- 解決Linux下Android开发真机调试设备不被识别问题
- [Android]在代码里运行另一个程序的方法
- [软件咨询]WPS2012正式版已发布 金山Office移动版4.0发布
- Android笔记-Linux Kernel Ftrace (Function Trace)解析
- C#基础:Dispose()、Close()、Finalize()的区别详解
- android USB如何修改VID具体实现
- Android增量升级的方法和原理详细介绍
- Android Mouse实现过程详细笔记
- 深入Android Browser配置管理的详解
- Android Mms之:深入理解对话列表管理
- Oracle索引(B*tree与Bitmap)的学习总结
- Android APP与媒体存储服务的交互
- android 多线程技术应用
- Android之采用execSQL与rawQuery方法完成数据的添删改查操作详解
- Android数据类型之间相互转换系统介绍
- 通过Android trace文件分析死锁ANR实例过程
- Android实现左右滑动效果的方法详解