android中Bitmap数据如何释放

       今天来研究一下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里面申请的资源!




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值