android中UI刷新如何实现的?

当我们自定义View的时候,我们会通过invalidate()来刷新UI,实现重绘。比如最简单的view.setVisibility()的调用路径:
------->view.setVisibility()
----------->view.view.setFlags()
-------------->View.requestLayout()
---------------->ViewGroup.requestLayout()
------------------>ViewRootImpl.requestLayout()
模拟一个非主线程刷新UI的异常,


android中UI刷新如何实现的?_第1张图片

更能看出最后一步ViewRootImpl.requestLayout()的调用。分析源码ViewRootImpl

 @Override
     public void requestLayout() {
         if (!mHandlingLayoutInLayoutRequest) {
             checkThread();
             mLayoutRequested = true;
             scheduleTraversals();
         }
     }
     .........
  void scheduleTraversals() {
         if (!mTraversalScheduled) {
             mTraversalScheduled = true;
             ......
             mChoreographer.postCallback(
                     Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
              .....
         }
     }

Choreographer中文意思是“编舞者”,是一个控制frame(帧)渲染信号的一个类。Choreographer方法doFrame(),处理四种类型的UI刷新的Callback有4种类型:
Input输入、Animation动画、Traversal绘制和布局,Commit是用来解决延迟信号的处理,即丢帧现象.

 void doFrame(long frameTimeNanos, int frame) {
         final long startNanos;
         synchronized (mLock) {
     .......
             mFrameInfo.markInputHandlingStart();
               //  Callback type: Input callback.  Runs first.
             doCallbacks(Choreographer.CALLBACK_INPUT, frameTimeNanos);
             //Callback type: Animation callback.  Runs before traversals.
             mFrameInfo.markAnimationsStart();
             doCallbacks(Choreographer.CALLBACK_ANIMATION, frameTimeNanos);
 
             mFrameInfo.markPerformTraversalsStart();
                  //CALLBACK_TRAVERSAL:Callback type: Traversal callback.  Handles layout and draw.  Runs after all other asynchronous messages have been handled.
             doCallbacks(Choreographer.CALLBACK_TRAVERSAL, frameTimeNanos);
            
                   //CALLBACK_COMMIT:Callback type: Commit callback.  Handles post-draw operations for the frame.
      * Runs after traversal completes. 
             doCallbacks(Choreographer.CALLBACK_COMMIT, frameTimeNanos);
         .......
     }

通过mChoreographer这个对象post任务mTraversalRunnable,该任务里只调用一个方法,doTraversal()。这个方法里在调用 performTraversals();

    final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }
void doTraversal() {
        if (mTraversalScheduled) {
            mTraversalScheduled = false;
         .......
            performTraversals();
         .....
        }
    }

performTraversals()方法里在调用performMeasure,performLayout,dispatchOnPreDraw实现测量,布局,绘制。

private void performTraversals() {
        // cache mView since it is used so much below...
        final View host = mView;
          ........
            if (!mStopped || mReportNextDraw) {
                    int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
                    int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
 
                    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
                   ......
                }
            }
        }  
              ........
        final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw);
        if (didLayout) {
            performLayout(lp, mWidth, mHeight);
        }
       .......
     if (!cancelDraw && !newSurface) {
           .......
            performDraw();
        }
    }

performDraw()方法中通过调用draw(fullRedrawNeeded);

private void performDraw() {
              .......    
       mIsDrawing = true;
       Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
       try {
           draw(fullRedrawNeeded);
       } finally {
           mIsDrawing = false;
           Trace.traceEnd(Trace.TRACE_TAG_VIEW);
       }
               .......
}

draw中绘制的时候按照支持硬件加速,和software两种绘制方式,

private void draw(boolean fullRedrawNeeded) {
        if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
                .......
                 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
             } else {
                ......
                 if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
                     return;
                 }
             }
}

mHardwareRenderer硬件加速渲染是ThreadedRenderer的一个对象,硬件加速渲染是通过 Display List来刷新的。通过RenderNode的实例化一个DisplayListCanvas.通过画布的DisplayListCanvas实现最终渲染。

  private void updateRootDisplayList(View view, HardwareDrawCallbacks callbacks) {
         Trace.traceBegin(Trace.TRACE_TAG_VIEW, "Record View#draw()");
         updateViewTreeDisplayList(view);
 
         if (mRootNodeNeedsUpdate || !mRootNode.isValid()) {
             DisplayListCanvas canvas = mRootNode.start(mSurfaceWidth, mSurfaceHeight);
             try {
                 final int saveCount = canvas.save();
                 canvas.translate(mInsetLeft, mInsetTop);
                 callbacks.onHardwarePreDraw(canvas);
 
                 canvas.insertReorderBarrier();
                 canvas.drawRenderNode(view.updateDisplayListIfDirty());
                 canvas.insertInorderBarrier();
 
                 callbacks.onHardwarePostDraw(canvas);
                 canvas.restoreToCount(saveCount);
                 mRootNodeNeedsUpdate = false;
             } finally {
                 mRootNode.end(canvas);
             }
         }
         Trace.traceEnd(Trace.TRACE_TAG_VIEW);
     }

非硬件加速的方式,即drawSoftware的方式,直接在Canvas上绘制,再通过 mView.draw(canvas)回调让子类继续自己的绘制。

 private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
             boolean scalingRequired, Rect dirty) {
 
         // Draw with software renderer.
         final Canvas canvas;
            canvas = mSurface.lockCanvas(dirty);
            //略掉
           //canvas.setXXX()
            // .....
         
             try {
                 canvas.translate(-xoff, -yoff);
                 if (mTranslator != null) {
                     mTranslator.translateCanvas(canvas);
                 }
                 canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
                 attachInfo.mSetIgnoreDirtyState = false;
 
                 mView.draw(canvas);
 
                 drawAccessibilityFocusedDrawableIfNeeded(canvas);
             } finally {
                 if (!attachInfo.mSetIgnoreDirtyState) {
                     // Only clear the flag if it was not set during the mView.draw() call
                     attachInfo.mIgnoreDirtyState = false;
                 }
             }
         
     }

再继续深入,就是RanderNode和Canvas调用地层native本地方法了。
如果你还不太了解硬件加速和非硬件加速渲染的区别,
推荐
Android硬件加速原理与实现简介

总结:

1.所有View的刷新都通过ViewRootImpl的 performTraversals()来实现测量,布局,绘制的。
2.Choreographer是一个控制frame(帧)渲染信号的一个类。Choreographer方法doFrame(),处理四种类型的UI刷新的Callback有4种类型:Input输入、Animation动画、Traversal绘制和布局,Commit是用来解决延迟信号的处理,即丢帧现象.
3.绘制UI的时候分两种方式,
硬件加速绘制条件下:RenderNode构建DisplayListCanvas,CPU用于控制复杂绘制逻辑、构建或更新DisplayList;GPU用于完成图形计算、渲染DisplayList。
软件绘制条件下:Canvas绘制构建Bitmap,CPU用于解码运算;bitmap传到底层,GPU直接渲染。
4.默认是software软件绘制,这种方式渲染效率低,硬件加速绘制优点高,原因是将复杂的图形计算在GPU上实现。避免过度重绘,减少CPU资源和压力。

源码连接:
ViewRootImpl
Choreographer
ThreadedRenderer
RenderNode

你可能感兴趣的:(android中UI刷新如何实现的?)