关于Android Bitmap

说到内存和性能优化,都会谈到Bitmap,经常会谈到recycle()方法。但是又有人说不需要调用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 && mNativePtr != 0) {
            if (nativeRecycle(mNativePtr)) {
                // 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;
        }
    }

简单总结下:

1. recycle()方法释放该Bitmap对应的 native object,清除了该bitmap的pixel data的饮用,但是没有立即释放 pixel data。

2. 一般情况下不需要主动调用,gc会处理bitmap的回收。如过需要立即释放bitmap对应的 native object,可以调用,但是要慎重。否则会出问题:

    java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap


以上是2.3以后的版本。2.3以前的需要主动调用recycle(). 因为2.3及以前的版本中,bitmap的数据是放在栈中而不是堆中。(gc回收主要回收堆中的内存)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值