Animation Drawable causing OutOfMemoryError on second run in Android

前端 未结 5 1125
傲寒
傲寒 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:29

    So, I manage to solve my problem with this approach:

    Created one AsyncTask for drawing

    private class DrawRabbit extends AsyncTask {    
         private int fps = 24;
         private int frame = 10014;
         private String drawableName; 
         @Override
           protected Void doInBackground(Void... params) {
             while (running){
               try {  
                if (frame == 10014)
                  Thread.sleep(1000);
                else 
                  Thread.sleep(fps);
              if (frame < 10160) { 
                frame++;
                publishProgress(frame);
              }
              else 
                running = false;
    
            } catch (InterruptedException e) { 
              e.printStackTrace();
            }
             }           
             return null;
           }
    
           protected void onProgressUpdate(Integer... frame) {
             drawableName = "rm" + frame[0];
             int res_id = getResources().getIdentifier(drawableName, "drawable", getPackageName());        
               rabbitFrame.setBackgroundResource(res_id);
           }   
       }
    

    and start it onWindowsFocusChanged

    public void onWindowFocusChanged(boolean hasFocus) {    
        super.onWindowFocusChanged(hasFocus);         
        if (hasFocus)
          new DrawRabbit().execute((Void)null) ;
        else 
          running = false;
        Log.d(TAG,"onFocusChanged");
      }
    

    Hope it helps someone!

提交回复
热议问题