最近听公司同事分享了一个android5.0新特性的介绍,其他的和本人负责模块相关性不大,没有特别关注,但是有一条比较有兴趣,就是renderthread的引入。说是终于能异步跑动画了,主线程堵塞不会导致动画卡了
流程和之前的完全一样,这个和renderthread没有关系。
view parent的ValueAnimator.AnimatorUpdateListener为空;
view parent的Animator.AnimatorListener为空;
view开启硬件加速,目前的android 4.4默认是开启硬件加速的;
view parent的hasActions()返回为false,这个函数我没有详细研究。
当四个条件都满足时,就使用renderthread渲染动画。
ViewPropertyAnimator使用线程渲染还是有很多限制的,但是其实可以直接用RenderNodeAnimator,因为它本身就是一个Animator
public class RenderNodeAnimator extends Animator
使用它就可以解决属性动画不能设置Listener等限制。
昨天从ftp上下了android5.0的源码,赶快看下renderthread到底对app的动画有啥影响。
1.最早的动画方式Animation
通过View.startAnimation(Animation animation)流程和之前的完全一样,这个和renderthread没有关系。
2.属性动画ViewPropertyAnimator
private void startAnimation() {
if (mRTBackend != null && mRTBackend.startAnimation(this)) {
return;
}
....
}
第一行代码就和renderthread建立了关系
/**
* A RenderThread-driven backend that may intercept startAnimation
*/
private ViewPropertyAnimatorRT mRTBackend;
mRTBackend类型为ViewPropertyAnimatorRT ,该类就是java层与renderthread建立关系的类。
/**
* @return true if ViewPropertyAnimatorRT handled the animation,
* false if ViewPropertyAnimator needs to handle it
*/
public boolean startAnimation(ViewPropertyAnimator parent) {
cancelAnimators(parent.mPendingAnimations);
if (!canHandleAnimator(parent)) {
return false;
}
doStartAnimation(parent);
return true;
}
canHandleAnimator是判断view是否可以启用renderthread,有四个条件:
view parent的ValueAnimator.AnimatorUpdateListener为空;
view parent的Animator.AnimatorListener为空;
view开启硬件加速,目前的android 4.4默认是开启硬件加速的;
view parent的hasActions()返回为false,这个函数我没有详细研究。
当四个条件都满足时,就使用renderthread渲染动画。
ViewPropertyAnimatorRT.doStartAnimation(ViewPropertyAnimator parent)
private void doStartAnimation(ViewPropertyAnimator parent)
RenderNodeAnimator animator = new RenderNodeAnimator(property, finalValue);
...
animator.start();
...
}
创建了RenderNodeAnimator 对象并启动动画,最终在java层的最后
private void doStart() {
mState = STATE_RUNNING;
nStart(mNativePtr.get(), this);
...
}
通过jni调用C层的代码。java层的代码流程到此结束。
3.RenderNodeAnimator
ViewPropertyAnimator使用线程渲染还是有很多限制的,但是其实可以直接用RenderNodeAnimator,因为它本身就是一个Animator
public class RenderNodeAnimator extends Animator
使用它就可以解决属性动画不能设置Listener等限制。
总结:
使用Animation和之前的流程一样,运行在主线程队列,没有享受renderthread的机制;使用属性动画可以享用rt的机制,但是有限制,如不能有设置AnimatorListener;想完全替代以前的动画,还是用RenderNodeAnimator 重写吧。本文完全是看代码分析的结果,我这里还没有5.0的机器验证,如有错误敬请指正。