网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

android中Bitmap数据如何释放

今天来研究一下android中的Bitmap。在实际开发中,Bitmap经常用到,特别是游戏开发。可以说游戏开发其实就是对图片(Bitmap)操作!可见Bitmap有多重要。这里我们主要讨论的是Bitmap资源释放原理。

成都创新互联是一家专业提供独山企业网站建设,专注与成都做网站、成都网站设计、H5响应式网站、小程序制作等业务。10年已为独山众多企业、政府机构等服务。创新互联专业的建站公司优惠进行中。

       我们知道,用完一个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里面申请的资源!


分享名称:android中Bitmap数据如何释放
分享路径:http://bjjierui.cn/article/picgdj.html

其他资讯