When activity destroy, unfortunately bitmap was not recycled if we're using Picasso. I try to programmatically recycle bitmap, what's loaded in to image view. There is a way to reference to loaded bitmap by using Target
.
Target mBackgroundTarget = new Target() {
Bitmap mBitmap;
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
if (bitmap == null || bitmap.isRecycled())
return;
mBitmap = bitmap;
mBgImage.setImageBitmap(bitmap);
mHandler.post(new Runnable() {
@Override
public void run() {
// Do some animation
}
});
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
recycle();
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
/**
* Recycle bitmap to free memory
*/
private void recycle() {
if (mBitmap != null && !mBitmap.isRecycled()) {
mBitmap.recycle();
mBitmap = null;
System.gc();
}
}
};
And when Activity destroy, I call onBitmapFailed(null)
to recycle loaded bitmap.
@Override
protected void onDestroy() {
super.onDestroy();
try {
if (mBackgroundTarget != null) {
mBackgroundTarget.onBitmapFailed(null);
Picasso.with(context).cancelRequest(mBackgroundTarget);
}
} catch (Exception e) {
e.printStackTrace();
}
}
But remember, DON'T CACHE IMAGE IN MEMORY by this case, It will cause Use recycled bitmap exception.
Picasso.with(context)
.load(imageUrl)
.resize(width, height)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.into(mBackgroundTarget);
Hope this help.