1. 程式人生 > >android很多圖片做成幀動畫造成記憶體溢位的解決方法。

android很多圖片做成幀動畫造成記憶體溢位的解決方法。

package com.familydoctor.widget;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;
import com.familydoctor.event.BaseEvent;
import com.familydoctor.event.EventCode;
import com.familydoctor.manager.EventManager;
/**
 * Created by kk on 2015/11/19.
 * ImageAnimation animation = new ImageAnimation(Iv_guide
(控制元件 ImageView, images (圖片資源 int[], 115 (每張圖片的時間間隔)); */ public class ImageAnimation { private Handler handler;//執行緒處理 private MovieAction action;//播放器 //固定迴圈時間 public ImageAnimation(ImageView view,int[] frameRes,int duration){ int len = frameRes.length; int [] frameDuration = new int
[len]; for(int i=0;i<len;i++){ frameDuration[i]=duration; } this.Init(view,frameRes,frameDuration); } //非固定迴圈時間 public ImageAnimation(ImageView view, int [] frameRes,int[] frameDuration){ this.Init(view,frameRes,frameDuration); } private void Init(ImageView view, int
[] frameRes,int[] frameDuration){ if(null==view) { Log.e("ImageAnimation", "建立動畫失敗。"); }else if(null == frameRes || null == frameDuration ||0 == frameRes.length ||0 == frameDuration.length) { Log.e("ImageAnimation", "幀數或資源為空."); }else if(frameRes.length != frameDuration.length){ Log.e("ImageAnimation","幀數與間隔時間不匹配"); }else { handler = new Handler(); action = new MovieAction(handler, view, frameRes, frameDuration); } } } //動畫播放類 class MovieAction implements Runnable{ private ImageView mView;//畫布 private int [] mFrameRes;//資源 private int[] mFrameDuration;//間隔 private int currentFrame;//當前幀 private int totalFrame;//總幀數 private Handler mHandler;//執行緒 public MovieAction(Handler handler,ImageView view, int [] frameRes,int[] frameDuration){ this.mView = view; this.mFrameRes = frameRes; this.mFrameDuration = frameDuration; this.mHandler = handler; totalFrame = this.mFrameRes.length; currentFrame = 0; mHandler.postDelayed(this, mFrameDuration[currentFrame]); } public void destory(){ this.mHandler.removeCallbacks(this); } /** * Starts executing the active part of the class' code. This method is * called when a thread is started that has been created with a class which * implements {@code Runnable}. */ @Override public void run() { mView.setBackgroundResource(mFrameRes[currentFrame]); currentFrame++; if(++currentFrame<totalFrame) { mHandler.postDelayed(this, mFrameDuration[currentFrame]); }else{ System.out.println("destory、、、、、"); destory(); EventManager.getInstance().DispatchEvent(new BaseEvent(EventCode.ShowBtn)); } } }