Animation Drawable causing OutOfMemoryError on second run in Android

前端 未结 5 1126
傲寒
傲寒 2020-12-05 11:57

I am currently developing a game and I\'m trying to use one AnimationDrawable to show one animation in my Main Menu. When I run the game once, it works perfectly. But if i t

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 12:27

    You need to free memory used by bitmaps, when you're exiting this screen. Unfortunately, for earlier versions of Android (afaik this was "fixed" since 3.0, but I can be wrong) memory for bitmaps is allocated through native code and, what is sad, memory should be freed explicitly.

    So, I suppose you to try this approach:

    1. Move code for AnimationDrawable to onResume() method.
    2. Add following code for releasing memory to onPause().

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

    I hope it'll help you.

提交回复
热议问题