關於Android Bitmap

分類:編程 時間:2017-02-12

說到內存和性能優化,都會談到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回收主要回收堆中的內存)


Tags:

文章來源:


ads
ads

相關文章
ads

相關文章

ad