Search code examples
androidimageviewandroid-imageviewandroid-bitmap

Checking if bitmap is recycled doesn't help to solve "RuntimeException: Canvas: trying to use a recycled bitmap"


I send bitmaps to my activity from Service (using LocalBroadcastManager and intent bitmap extra)

I set them to ImageView in activity like this:

if (!bitmap.isRecycled) {
    imageView.setImageBitmap(bitmap)
}

When I don't need the service anymore I close it and release bitmap object kept in that service

But when I close the service I usually get the following error:

java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@fc4b896

Sobitmap.isRecycled condition doesn't help here

Is there any safe method to set Bitmap to ImageView?


Solution

  • When you are using imageView.setImageBitmap(bitmap), you should not recycle the bitmap after setImageBitmap because your imageView is still referencing and using that bitmap. You can recycle it when activity/fragment/view is destroyed.