说到内存和性能优化,都会谈到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回收主要回收堆中的内存)