androidanimationdrawable

Android AnimationDrawable Recycling issue


I have a AnimationDrawable that i initialise before starting the animation and recycle it right as it finishes.. the problem is that when i want to start the animation again, i reinitialise everything but still gives an exception

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

here's my code

 public ImageView radarImageView;
 public AnimationDrawable animationDrawable;

    public void animationStart() {

//        animationStop();

        radarImageView = (ImageView) findViewById(R.id.radarIV);
        radarImageView.setBackgroundResource(R.drawable.sensor_animation);
        animationDrawable = (AnimationDrawable) radarImageView.getBackground();

        animationDrawable.start();
    }

    public void animationStop() {

        animationDrawable.stop();

        for (int i = 0; i < animationDrawable.getNumberOfFrames(); ++i){
            Drawable frame = animationDrawable.getFrame(i);
            if (frame instanceof BitmapDrawable) {
                ((BitmapDrawable)frame).getBitmap().recycle();
            }
            frame.setCallback(null);
        }
        animationDrawable.setCallback(null);

//        animationDrawable = null;
//        radarImageView.setBackgroundResource(0);
    }

Why does it not reinitialise the whole thing again?


Solution

  • The problem is because when you Bitmap.recycle() is called on the bitmap you cannot reuse it.

    Also as you are calling setBackgroundResources(R.drawable.sensor_animation) you are referring to the same object which its bitmaps were recycled previously.

    As a solution, you either have to create a new drawable every time or do not recycle that instance.

    If you are worries about the memory usage try to use smaller bitmaps. Also using the correct sizes for different screen densities would help.