How to fix "canvas: trying to use a recycled bitmap error"?
I suspect that once in a while your bitmap gets into the recycled state just before the Canvas
gets a chance to draw onto it here drawable.draw(canvas);
.
A quick solution should be not to call bitmap.recycle();
, which is not strictly required for android >2.3.3. If you still want to reclaim this memory forcefully, you'll have to find a way to check when the bitmap is indeed no longer needed (i.e., Canvas
had a chance to finish its drawing operations).
Use this custom ImageView class
public class MyImageView extends ImageView {
public MyImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyImageView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
try {
super.onDraw(canvas);
} catch (Exception e) {
Log.i(MyImageView.class.getSimpleName(), "Catch Canvas: trying to use a recycled bitmap");
}
}
}
Move bitmap.recycle();
to another place in the code where this bitmap is really no longer needed.