1.
很多人都知道为了减小图片对资源的消耗会调用Bitmap.recycle();然后再调用Bitmap=null;但是在Bitmap.recycle();的时候Bitmap到底是回收了什么,把什么回收了?
想知道recycle到底是recycle了什么,最直接的方法就是读fucking resource code
/** * 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 && mFinalizer.mNativeBitmap != 0) { 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; } }好,先用翻译工具将Google给的注释翻译一下,大概意思就是这样的:
释放与此位图相关联的本机对象,并清除参考像素数据。这将不会同步地释放像素数据;它只是允许在没有其他引用的情况下收集垃圾。位图被标记为“死”,意味着它将抛出一个异常get像素()或setpx()被调用,什么也不画。这个操作不能颠倒,所以只有在你确定没有的时候才应该调用它进一步使用位图。这是一个高级调用,通常不需要调用,因为正常的GC进程将释放这个内存,因为不再有对这个位图的引用
将这一大句话简化一下意思就是说:Bitmap.recycle();会释放Bitmap所关联的像素资源,并且释放是单向的,一旦释放不可再用。
这样的话就好理解了,Bitmap.recycle();释放了图片的资源,但是Bitmap本身并没有释放,它依然在占用资源,所以还要在调用一次Bitmap=null;将Bitmap赋空,让有向图断掉,好让GC回收。