Android 逐帧动画oom解决办法

来源:互联网 发布:用js写九九乘法表 编辑:程序博客网 时间:2024/05/16 00:50

核心思想:复用图片资源

功能实现:定制AnimationDrawable


贴代码

public class CustomAnimationDrawable extends AnimationDrawable {public interface CallBack {void onEnd(AnimationDrawable animationDrawable);}private CustomAnimationDrawable.CallBackcallback;private intmCurrentIndex= -1;private Map<Integer, Integer>res= new HashMap<Integer, Integer>();private List<Integer>ids= new ArrayList<Integer>();private LruCache<Integer, BitmapDrawable>cache= ImageCache.CACHE;private Resourcesresources;public CustomAnimationDrawable(Resources resources) {this.resources = resources;}int pageIndex = 0;@Overridepublic void start() {super.start();mCurrentIndex = 0;}@Overridepublic void stop() {// TODO Auto-generated method stubsuper.stop();mCurrentIndex = 0;}@Overridepublic void addFrame(Drawable frame, int duration) {// TODO Auto-generated method stubsuper.addFrame(frame, duration);}public void addFrame(int frame, int duration) {// TODO Auto-generated method stubres.put(frame, duration);ids.add(frame);}@SuppressWarnings("deprecation")public void init() {for (int i = 0;i < ids.size(); i++) {pageIndex = i;if (null==cache.get(ids.get(i))||cache.get(ids.get(i)).getBitmap().isRecycled()) {Options opts = new Options();opts.inSampleSize = 2;Bitmap bitmap = BitmapFactory.decodeResource(resources, ids.get(i), opts);BitmapDrawable framed = new BitmapDrawable(bitmap);addFrame(framed, res.get(ids.get(i)));cache.put(ids.get(i), framed);}else{addFrame(cache.get(ids.get(i)), res.get(ids.get(i)));}}}@Overridepublic void run() {// TODO Auto-generated method stubif (cache.size() <= 0||getNumberOfFrames()<=0) {init();}super.run();if (isLast()) {System.gc();}}private boolean isLast() {if (getNumberOfFrames() <= 1) {if (null != callback) {callback.onEnd(this);}return true;}if (mCurrentIndex != -1) {mCurrentIndex++;if (mCurrentIndex >= getNumberOfFrames() - 1) {if (null != callback) {callback.onEnd(this);}return true;}return false;}int currentIndex = 0;Field field = null;try {field = this.getClass().getSuperclass().getDeclaredField("mCurFrame");}catch (NoSuchFieldException e) {// TODO Auto-generated catch blocke.printStackTrace();}field.setAccessible(true);try {currentIndex = field.getInt(this);mCurrentIndex = currentIndex;}catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();}field.setAccessible(false);if (currentIndex >= getNumberOfFrames() && !isOneShot()) {if (null != callback) {callback.onEnd(this);}return true;}return false;}public void setCallback2(CallBack callback) {this.callback = callback;}
}


0 0
原创粉丝点击