我们知道手机的内存有限,而图片所占的内存往往又很大。所以在处理图片的时候可以在服务端或者客户端提前将图片处理一下,减少其体积。另外使用Bitmap的时候可以使用SoftReference来及时释放资源。但是看到好多程序还是主动地调用Bitmap对象的recycle方法来释放资源。可能我们就有疑问了:不是java会自动回收内存吗,那干吗还要手动地去回收?
要解决这个问题,我们得去看看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) {
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;
}
}
通过看源码,我们会发现,这个方法首先将这个Bitmap的引用置为null,然后调用了nativeRecycle(mNativeBitMap)方法,这个方法很明显是个JNI调用,会调用底层的c或者c++代码就可以做到对该内存的立即回收,而不需要等待那不确定啥时候会执行的GC来回收了。
当然如果用的图片很少,占用的内存也很少的时候就没有必要手动调用recycle方法来回收内存了,GC会在合适的时候回收这些内存的。只有图片很多占用内存很多的时候才需要我们主动调用recycle方法,否则很有可能出现OOM异常的。