今天来研究一下android中的Bitmap。在实际开发中,Bitmap经常用到,特别是游戏开发。可以说游戏开发其实就是对图片(Bitmap)操作!可见Bitmap有多重要。这里我们主要讨论的是Bitmap资源释放原理。
我们知道,用完一个Bitmap后,需要马上recycle()来保证尽快释放期资源。首先,我们来看看recycle()这个函数的定义(Bitmap.java):
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里面申请的资源!