分析Android属性动画源码的执行过程

我们从启动动画为着手点分析属性动画的执行过程

@Override
public void start() {    
  AnimationHandler.getInstance().autoCancelBasedOn(this);    
  if (DBG) {        
    Log.d(LOG_TAG, "Anim target, duration: " + getTarget() + ", " + getDuration());        
    for (int i = 0; i < mValues.length; ++i) {            
      PropertyValuesHolder pvh = mValues[i];            
      Log.d(LOG_TAG, "Values[" + i + "]: " + pvh.getPropertyName() + ", " + pvh.mKeyframes.getValue(0) + ", " + pvh.mKeyframes.getValue(1));        
    }    
  }    
  super.start();
}

该段代码只需看第一行和最后一行,第一行代码为查看ThreadLocal中是否有AnimationHandler实例,并为其赋初值,如果mAnimationCallbacks这个ArrayList中有保存回调,那么遍历该ArrayList并查看元素是否应该自动取消,最后一行调用了父类的start方法,那么我们就查看下ValueAnimator中的start方法

@Overridepublic void start() {    
  start(false);
}
private void start(boolean playBackwards) {
  if (Looper.myLooper() == null) {        
      throw new AndroidRuntimeException("Animators may only be run on Looper threads");    
  }    
  mReversing = playBackwards;    
  // Special case: reversing from seek-to-0 should act as if not seeked at all.    
  if (playBackwards && mSeekFraction != -1 && mSeekFraction != 0) {
      if (mRepeatCount == INFINITE) {            
          // Calculate the fraction of the current iteration.            
          float fraction = (float) (mSeekFraction - Math.floor(mSeekFraction));
          mSeekFraction = 1 - fraction;        
      } else {
          mSeekFraction = 1 + mRepeatCount - mSeekFraction;
      }    
  }    
  mStarted = true;    
  mPaused = false;    
  mRunning = false;    
  // Resets mLastFrameTime when start() is called, so that if the animation was running,    
  // calling start() would put the animation in the    
  // started-but-not-yet-reached-the-first-frame phase.    
  mLastFrameTime = 0;    
  AnimationHandler animationHandler = AnimationHandler.getInstance();
  animationHandler.addAnimationFrameCallback(this, (long) (mStartDelay * sDurationScale));    
  if (mStartDelay == 0 || mSeekFraction >= 0) {        
    // If there's no start delay, init the animation and notify start listeners right away        
      // to be consistent with the previous behavior. Otherwise, postpone this until the first        
      // frame after the start delay.        
      startAnimation();        
      if (mSeekFraction == -1) {            
      // No seek, start at play time 0. Note that the reason we are not using fraction 0            
      // is because for animations with 0 duration, we want to be consistent with pre-N           
      // behavior: skip to the final value immediately.            
        setCurrentPlayTime(0);        
      } else {            
          setCurrentFraction(mSeekFraction);        
      }    
  }
}

可以看出动画时运行在有Looper中的线程中的(为什么要在Looper中因为之后的代码使用到了Handler),我们看到
animationHandler.addAnimationFrameCallback(this, (long) (mStartDelay * sDurationScale));让我们走进这行代码深究一下

public void addAnimationFrameCallback(final AnimationFrameCallback callback, long delay) {    
    if (mAnimationCallbacks.size() == 0) {
        getProvider().postFrameCallback(mFrameCallback);    
    }    
    if (!mAnimationCallbacks.contains(callback)) {
        mAnimationCallbacks.add(callback);    
    }    
    if (delay > 0) {        
        mDelayedCallbackStartTime.put(callback, (SystemClock.uptimeMillis() + delay));    
    }
}
getProvider()返回的是MyFrameCallbackProvider的实例,而MyFrameCallbackProvider由实现了AnimationFrameCallbackProvider接口,所以让我们愉快的查看MyFrameCallbackProvider中的postFrameCallback方法
@Overridepublic void postFrameCallback(Choreographer.FrameCallback callback) {  
    mChoreographer.postFrameCallback(callback);
}

该方法内部逐层调用最终调用了

private void postCallbackDelayedInternal(int callbackType, Object action, Object token, long delayMillis) {    
    if (DEBUG_FRAMES) {        
        Log.d(TAG, "PostCallback: type=" + callbackType + ", action=" + action + ", token=" + token + ", delayMillis=" + delayMillis);    
    }    
    synchronized (mLock) {        
        final long now = SystemClock.uptimeMillis();        
        final long dueTime = now + delayMillis;
        mCallbackQueues[callbackType].addCallbackLocked(dueTime, action, token);       
        if (dueTime <= now) {           
           scheduleFrameLocked(now);       
        } else {           
           Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_CALLBACK, action);         
           msg.arg1 = callbackType;   
           msg.setAsynchronous(true); 
           mHandler.sendMessageAtTime(msg, dueTime);    
        }  
    }
}

我们看到这里使用到了Handler,所以这就解释了为什么前面需要检查Looper是否为空了。我们可以看到逻辑是如果有延迟那么就运行else方法,没有设置延迟都是调用scheduleFrameLocked方法

private void scheduleFrameLocked(long now) {    
   if (!mFrameScheduled) {        
      mFrameScheduled = true;        
      if (USE_VSYNC) {            
          if (DEBUG_FRAMES) {                
              Log.d(TAG, "Scheduling next frame on vsync.");           
          }           
          // If running on the Looper thread, then schedule the vsync immediately,
         // otherwise post a message to schedule the vsync from the UI thread
        // as soon as possible.
          if (isRunningOnLooperThreadLocked()) {
              scheduleVsyncLocked();
          } else {
              Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_VSYNC);
              msg.setAsynchronous(true); 
              mHandler.sendMessageAtFrontOfQueue(msg);
          }
      } else {
          final long nextFrameTime = Math.max(mLastFrameTimeNanos / TimeUtils.NANOS_PER_MS + sFrameDelay, now);
          if (DEBUG_FRAMES) {
              Log.d(TAG, "Scheduling next frame in " + (nextFrameTime - now) + " ms.");
          }
          Message msg = mHandler.obtainMessage(MSG_DO_FRAME);            
          msg.setAsynchronous(true);
          mHandler.sendMessageAtTime(msg, nextFrameTime);
      }
   }
}

我们看出最后运行的是scheduleVsyncLocked();方法,而该方法内部调用的是native方法。因为之前调用传递的是Choreographer.FrameCallback实例,所以最终因该会调用该实例的doFrame方法,而会调用AnimationHandler的doAnimationFrame方法,而该方法又会调用ValueAnimator的doAnimationFrame方法

public final void doAnimationFrame(long frameTime) {
    AnimationHandler handler = AnimationHandler.getInstance();
    if (mLastFrameTime == 0) {
        // First frame
        handler.addOneShotCommitCallback(this);
        if (mStartDelay > 0) {
            startAnimation();
        }
        if (mSeekFraction < 0) {
            mStartTime = frameTime;
        } else {
            long seekTime = (long) (getScaledDuration() * mSeekFraction);            mStartTime = frameTime - seekTime;
            mSeekFraction = -1;
        }
        mStartTimeCommitted = false; // allow start time to be compensated for jank
    }
    mLastFrameTime = frameTime;
    if (mPaused) {
        mPauseTime = frameTime;
        handler.removeCallback(this);
        return;
    } else if (mResumed) {
        mResumed = false;
        if (mPauseTime > 0) {
            // Offset by the duration that the animation was paused
            mStartTime += (frameTime - mPauseTime);
            mStartTimeCommitted = false; // allow start time to be compensated for jank
        }
        handler.addOneShotCommitCallback(this);
    }
    // The frame time might be before the start time during the first frame of
    // an animation.  The "current time" must always be on or after the start
    // time to avoid animating frames at negative time intervals.  In practice, this
    // is very rare and only happens when seeking backwards.
    final long currentTime = Math.max(frameTime, mStartTime);
    boolean finished = animateBasedOnTime(currentTime);
    if (finished) {
        endAnimation();
    }
}

我们看到从animateBasedOnTime(currentTime);方法的返回值用于判断是否结束动画

boolean animateBasedOnTime(long currentTime) {
    boolean done = false;
    if (mRunning) {
        final long scaledDuration = getScaledDuration();
        final float fraction = scaledDuration > 0 ? (float)(currentTime - mStartTime) / scaledDuration : 1f;
        final float lastFraction = mOverallFraction;
        final boolean newIteration = (int) fraction > (int) lastFraction;
        final boolean lastIterationFinished = (fraction >= mRepeatCount + 1) && (mRepeatCount != INFINITE);
        if (scaledDuration == 0) {
            // 0 duration animator, ignore the repeat count and skip to the end
            done = true;
        } else if (newIteration && !lastIterationFinished) {
            // Time to repeat
            if (mListeners != null) {
                int numListeners = mListeners.size();
                for (int i = 0; i < numListeners; ++i) {
                    mListeners.get(i).onAnimationRepeat(this);
                }
            }
        } else if (lastIterationFinished) {
            done = true;
        }
        mOverallFraction = clampFraction(fraction);
        float currentIterationFraction = getCurrentIterationFraction(mOverallFraction);
        animateValue(currentIterationFraction);
    }
    return done;
}
@CallSupervoid animateValue(float fraction) {
    fraction = mInterpolator.getInterpolation(fraction);
    mCurrentFraction = fraction;
    int numValues = mValues.length;
    for (int i = 0; i < numValues; ++i) {
        mValues[i].calculateValue(fraction);
    }
    if (mUpdateListeners != null) {
        int numListeners = mUpdateListeners.size();
        for (int i = 0; i < numListeners; ++i) {
            mUpdateListeners.get(i).onAnimationUpdate(this);
        }
    }
}

我们看到calculateValue(fraction);方法使用PropertyValuesHolder中的calculateValue去计算值。

未完善,待续。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,222评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,455评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,720评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,568评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,696评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,879评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,028评论 3 409
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,773评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,220评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,550评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,697评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,360评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,002评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,782评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,010评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,433评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,587评论 2 350

推荐阅读更多精彩内容