View的绘制流程

作者: Chase_stars | 来源:发表于2019-07-27 00:15 被阅读3次

    我读的书愈多,就愈亲近世界,愈明了生活的意义,愈觉得生活的重要。— 高尔基

    写在前面

    View翻译成中文就是“视图”,可想而知,View一定是肉眼可见的,其实在应用开发中只要存在界面就一定有View,View要将数据展示给用户,View不仅仅用于展示数据,好看的界面也能够吸引用户的眼球。本篇我们就来学习下View是怎么工作的。

    创建视图

    在调用startActivity()启动一个Activity时,最终会调用到ActivityThread的handleLaunchActivity(),所以我们从该方法开始。

    1.创建Activity
    public final class ActivityThread extends ClientTransactionHandler {
    
          /**
         * Extended implementation of activity launch. Used when server requests a launch or relaunch.
         */
        @Override
        public Activity handleLaunchActivity(ActivityClientRecord r,
                PendingTransactionActions pendingActions, Intent customIntent) {
            // If we are getting ready to gc after going to the background, well
            // we are back active so skip it.
            unscheduleGcIdler();
            mSomeActivitiesChanged = true;
    
            if (r.profilerInfo != null) {
                mProfiler.setProfiler(r.profilerInfo);
                mProfiler.startProfiling();
            }
    
            // Make sure we are running with the most recent config.
            handleConfigurationChanged(null, null);
    
            if (localLOGV) Slog.v(
                TAG, "Handling launch of " + r);
    
            // Initialize before creating the activity
            if (!ThreadedRenderer.sRendererDisabled) {
                GraphicsEnvironment.earlyInitEGL();
            }
            WindowManagerGlobal.initialize();
    
            final Activity a = performLaunchActivity(r, customIntent); // 1
    
            if (a != null) {
                r.createdConfig = new Configuration(mConfiguration);
                reportSizeConfigurations(r);
                if (!r.activity.mFinished && pendingActions != null) {
                    pendingActions.setOldState(r.state);
                    pendingActions.setRestoreInstanceState(true);
                    pendingActions.setCallOnPostCreate(true);
                }
            } else {
                // If there was an error, for any reason, tell the activity manager to stop us.
                try {
                    ActivityManager.getService()
                            .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                                    Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
                } catch (RemoteException ex) {
                    throw ex.rethrowFromSystemServer();
                }
            }
    
            return a;
        }
    
        /**  Core implementation of activity launch. */
        private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
            ActivityInfo aInfo = r.activityInfo;
            if (r.packageInfo == null) {
                r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                        Context.CONTEXT_INCLUDE_CODE);
            }
    
            ComponentName component = r.intent.getComponent();
            if (component == null) {
                component = r.intent.resolveActivity(
                    mInitialApplication.getPackageManager());
                r.intent.setComponent(component);
            }
    
            if (r.activityInfo.targetActivity != null) {
                component = new ComponentName(r.activityInfo.packageName,
                        r.activityInfo.targetActivity);
            }
    
            ContextImpl appContext = createBaseContextForActivity(r);
            Activity activity = null;
            try {
                java.lang.ClassLoader cl = appContext.getClassLoader();
                activity = mInstrumentation.newActivity(
                        cl, component.getClassName(), r.intent);
                StrictMode.incrementExpectedActivityCount(activity.getClass());
                r.intent.setExtrasClassLoader(cl);
                r.intent.prepareToEnterProcess();
                if (r.state != null) {
                    r.state.setClassLoader(cl);
                }
            } catch (Exception e) {
                if (!mInstrumentation.onException(activity, e)) {
                    throw new RuntimeException(
                        "Unable to instantiate activity " + component
                        + ": " + e.toString(), e);
                }
            }
    
            try {
                Application app = r.packageInfo.makeApplication(false, mInstrumentation);
    
                if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
                if (localLOGV) Slog.v(
                        TAG, r + ": app=" + app
                        + ", appName=" + app.getPackageName()
                        + ", pkg=" + r.packageInfo.getPackageName()
                        + ", comp=" + r.intent.getComponent().toShortString()
                        + ", dir=" + r.packageInfo.getAppDir());
    
                if (activity != null) {
                    CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                    Configuration config = new Configuration(mCompatConfiguration);
                    if (r.overrideConfig != null) {
                        config.updateFrom(r.overrideConfig);
                    }
                    if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                            + r.activityInfo.name + " with config " + config);
                    Window window = null;
                    if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                        window = r.mPendingRemoveWindow;
                        r.mPendingRemoveWindow = null;
                        r.mPendingRemoveWindowManager = null;
                    }
                    appContext.setOuterContext(activity);
                    activity.attach(appContext, this, getInstrumentation(), r.token,
                            r.ident, app, r.intent, r.activityInfo, title, r.parent,
                            r.embeddedID, r.lastNonConfigurationInstances, config,
                            r.referrer, r.voiceInteractor, window, r.configCallback); // 2
    
                    if (customIntent != null) {
                        activity.mIntent = customIntent;
                    }
                    r.lastNonConfigurationInstances = null;
                    checkAndBlockForNetworkAccess();
                    activity.mStartedActivity = false;
                    int theme = r.activityInfo.getThemeResource();
                    if (theme != 0) {
                        activity.setTheme(theme);
                    }
    
                    activity.mCalled = false;
                    if (r.isPersistable()) {
                        mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                    } else {
                        mInstrumentation.callActivityOnCreate(activity, r.state); // 3
                    }
                    if (!activity.mCalled) {
                        throw new SuperNotCalledException(
                            "Activity " + r.intent.getComponent().toShortString() +
                            " did not call through to super.onCreate()");
                    }
                    r.activity = activity;
                }
                r.setState(ON_CREATE);
    
                mActivities.put(r.token, r);
    
            } catch (SuperNotCalledException e) {
                throw e;
    
            } catch (Exception e) {
                if (!mInstrumentation.onException(activity, e)) {
                    throw new RuntimeException(
                        "Unable to start activity " + component
                        + ": " + e.toString(), e);
                }
            }
    
            return activity;
        }
    }
    

    从注释1处可以看到handleLaunchActivity()内部调用performLaunchActivity()并接收到一个Activity,其实performLaunchActivity()内部创建了一个Activity,返回值就是这个Activity。那么就直接看performLaunchActivity()内部注释2处,Activity创建成功了并调用了Activity的attach()方法,在注释3处调用了Instrumentation的callActivityOnCreate(activity, r.state),并将Activity作为参数传入。

    2.调用onCreate()
    public class Instrumentation {
    
        /**
         * Perform calling of an activity's {@link Activity#onCreate}
         * method.  The default implementation simply calls through to that method.
         *
         * @param activity The activity being created.
         * @param icicle The previously frozen state (or null) to pass through to onCreate().
         */
        public void callActivityOnCreate(Activity activity, Bundle icicle) {
            prePerformCreate(activity);
            activity.performCreate(icicle); // 1
            postPerformCreate(activity);
        }
    }
    

    从注释1处可以看到callActivityOnCreate(activity, r.state)方法内部调用了Activity的performCreate(icicle)方法。

    public class Activity extends ContextThemeWrapper
            implements LayoutInflater.Factory2,
            Window.Callback, KeyEvent.Callback,
            OnCreateContextMenuListener, ComponentCallbacks2,
            Window.OnWindowDismissedCallback, WindowControllerCallback,
            AutofillManager.AutofillClient {
    
        final void performCreate(Bundle icicle) {
            performCreate(icicle, null);
        }
    
        final void performCreate(Bundle icicle, PersistableBundle persistentState) {
            mCanEnterPictureInPicture = true;
            restoreHasCurrentPermissionRequest(icicle);
            if (persistentState != null) {
                onCreate(icicle, persistentState);
            } else {
                onCreate(icicle); // 1
            }
            writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
            mActivityTransitionState.readState(icicle);
    
            mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
                    com.android.internal.R.styleable.Window_windowNoDisplay, false);
            mFragments.dispatchActivityCreated();
            mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
        }
    }
    

    从注释1处可以看到onCreate()被调用了。在应用开发中,使用Activity时往往要写一个子类继承自Activity,重写onCreate()方法并调用setContentView()添加布局。

    3.添加布局
    public class Activity extends ContextThemeWrapper
            implements LayoutInflater.Factory2,
            Window.Callback, KeyEvent.Callback,
            OnCreateContextMenuListener, ComponentCallbacks2,
            Window.OnWindowDismissedCallback, WindowControllerCallback,
            AutofillManager.AutofillClient {
    
        final void attach(Context context, ActivityThread aThread,
                Instrumentation instr, IBinder token, int ident,
                Application application, Intent intent, ActivityInfo info,
                CharSequence title, Activity parent, String id,
                NonConfigurationInstances lastNonConfigurationInstances,
                Configuration config, String referrer, IVoiceInteractor voiceInteractor,
                Window window, ActivityConfigCallback activityConfigCallback) {
            attachBaseContext(context);
    
            mFragments.attachHost(null /*parent*/);
    
            mWindow = new PhoneWindow(this, window, activityConfigCallback); // 1
           
            ......
    
        }
    
        public void setContentView(@LayoutRes int layoutResID) {
            getWindow().setContentView(layoutResID); // 2
            initWindowDecorActionBar();
        }
    
        public Window getWindow() {
            return mWindow;
        }
    }
    

    首先看setContentView()方法,注释2处调用了getWindow().setContentView(layoutResID),getWindow()返回的是mWindow,mWindow在attach()方法中注释1处通过new PhoneWindow(this, window, activityConfigCallback)创建的,Window是一个抽象类,PhoneWindow继承自Window,是Window的实现类,所以getWindow().setContentView(layoutResID)实则调用了PhoneWindow的setContentView(layoutResID)方法。

    public class PhoneWindow extends Window implements MenuBuilder.Callback {
    
        @Override
        public void setContentView(int layoutResID) {
            // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
            // decor, when theme attributes and the like are crystalized. Do not check the feature
            // before this happens.
            if (mContentParent == null) {
                installDecor(); // 1
            } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
                mContentParent.removeAllViews();
            }
    
            if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
                final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                        getContext());
                transitionTo(newScene);
            } else {
                mLayoutInflater.inflate(layoutResID, mContentParent); // 2
            }
            mContentParent.requestApplyInsets();
            final Callback cb = getCallback();
            if (cb != null && !isDestroyed()) {
                cb.onContentChanged();
            }
            mContentParentExplicitlySet = true;
        }
    
        @Override
        public void setContentView(View view) {
            setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
        }
    
        @Override
        public void setContentView(View view, ViewGroup.LayoutParams params) {
            // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
            // decor, when theme attributes and the like are crystalized. Do not check the feature
            // before this happens.
            if (mContentParent == null) {
                installDecor();
            } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
                mContentParent.removeAllViews();
            }
    
            if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
                view.setLayoutParams(params);
                final Scene newScene = new Scene(mContentParent, view);
                transitionTo(newScene);
            } else {
                mContentParent.addView(view, params);
            }
            mContentParent.requestApplyInsets();
            final Callback cb = getCallback();
            if (cb != null && !isDestroyed()) {
                cb.onContentChanged();
            }
            mContentParentExplicitlySet = true;
        }
    
        private void installDecor() {
            mForceDecorInstall = false;
            if (mDecor == null) {
                mDecor = generateDecor(-1); // 3
                mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
                mDecor.setIsRootNamespace(true);
                if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                    mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
                }
            } else {
                mDecor.setWindow(this);
            }
            if (mContentParent == null) {
                mContentParent = generateLayout(mDecor); // 4
    
            ......
              
        }
    
        protected DecorView generateDecor(int featureId) {
            // System process doesn't have application context and in that case we need to directly use
            // the context we have. Otherwise we want the application context, so we don't cling to the
            // activity.
            Context context;
            if (mUseDecorContext) {
                Context applicationContext = getContext().getApplicationContext();
                if (applicationContext == null) {
                    context = getContext();
                } else {
                    context = new DecorContext(applicationContext, getContext());
                    if (mTheme != -1) {
                        context.setTheme(mTheme);
                    }
                }
            } else {
                context = getContext();
            }
            return new DecorView(context, featureId, this, getAttributes()); // 5
        }
    
       protected ViewGroup generateLayout(DecorView decor) {
            
            ......
            
            // 6
            // Inflate the window decor.
    
            int layoutResource;
            int features = getLocalFeatures();
            // System.out.println("Features: 0x" + Integer.toHexString(features));
            if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
                layoutResource = R.layout.screen_swipe_dismiss;
                setCloseOnSwipeEnabled(true);
            } else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
                if (mIsFloating) {
                    TypedValue res = new TypedValue();
                    getContext().getTheme().resolveAttribute(
                            R.attr.dialogTitleIconsDecorLayout, res, true);
                    layoutResource = res.resourceId;
                } else {
                    layoutResource = R.layout.screen_title_icons;
                }
                // XXX Remove this once action bar supports these features.
                removeFeature(FEATURE_ACTION_BAR);
                // System.out.println("Title Icons!");
            } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
                    && (features & (1 << FEATURE_ACTION_BAR)) == 0) {
                // Special case for a window with only a progress bar (and title).
                // XXX Need to have a no-title version of embedded windows.
                layoutResource = R.layout.screen_progress;
                // System.out.println("Progress!");
            } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
                // Special case for a window with a custom title.
                // If the window is floating, we need a dialog layout
                if (mIsFloating) {
                    TypedValue res = new TypedValue();
                    getContext().getTheme().resolveAttribute(
                            R.attr.dialogCustomTitleDecorLayout, res, true);
                    layoutResource = res.resourceId;
                } else {
                    layoutResource = R.layout.screen_custom_title;
                }
                // XXX Remove this once action bar supports these features.
                removeFeature(FEATURE_ACTION_BAR);
            } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
                // If no other features and not embedded, only need a title.
                // If the window is floating, we need a dialog layout
                if (mIsFloating) {
                    TypedValue res = new TypedValue();
                    getContext().getTheme().resolveAttribute(
                            R.attr.dialogTitleDecorLayout, res, true);
                    layoutResource = res.resourceId;
                } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
                    layoutResource = a.getResourceId(
                            R.styleable.Window_windowActionBarFullscreenDecorLayout,
                            R.layout.screen_action_bar);
                } else {
                    layoutResource = R.layout.screen_title;
                }
                // System.out.println("Title!");
            } else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
                layoutResource = R.layout.screen_simple_overlay_action_mode;
            } else {
                // Embedded, so no decoration is needed.
                layoutResource = R.layout.screen_simple;
                // System.out.println("Simple!");
            }
    
            mDecor.startChanging();
            mDecor.onResourcesLoaded(mLayoutInflater, layoutResource); // 7
    
            ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT); // 8
            if (contentParent == null) {
                throw new RuntimeException("Window couldn't find content container view");
            }
    
            if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
                ProgressBar progress = getCircularProgressBar(false);
                if (progress != null) {
                    progress.setIndeterminate(true);
                }
            }
    
            if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
                registerSwipeCallbacks(contentParent);
            }
    
            // Remaining setup -- of background and title -- that only applies
            // to top-level windows.
            if (getContainer() == null) {
                final Drawable background;
                if (mBackgroundResource != 0) {
                    background = getContext().getDrawable(mBackgroundResource);
                } else {
                    background = mBackgroundDrawable;
                }
                mDecor.setWindowBackground(background);
    
                final Drawable frame;
                if (mFrameResource != 0) {
                    frame = getContext().getDrawable(mFrameResource);
                } else {
                    frame = null;
                }
                mDecor.setWindowFrame(frame);
    
                mDecor.setElevation(mElevation);
                mDecor.setClipToOutline(mClipToOutline);
    
                if (mTitle != null) {
                    setTitle(mTitle);
                }
    
                if (mTitleColor == 0) {
                    mTitleColor = mTextColor;
                }
                setTitleColor(mTitleColor);
            }
    
            mDecor.finishChanging();
    
            return contentParent;
        }
    }
    

    这里只看最常用的setContentView(int layoutResID)方法,第一次调用setContentView()方法mContentParent一定是空的,所以会调用注释1处的installDecor()方法给mContentParent赋值,在注释2处会调用mLayoutInflater.inflate(layoutResID, mContentParent)将布局添加到mContentParent。

    现在来看注释1处installDecor()方法做了什么,注释3处调用了generateDecor(-1)方法并将返回值赋给mDecor,generateDecor()方法在最后注释5处创建了一个DecorView作为返回值,DecorView继承自FrameLayout,DecorView就是个布局容器。此时DecorView创建成功了,但是mContentParent还是没有值,在注释4处调用了generateLayout(mDecor)方法并将返回值赋值给mContentParent,那么就来看看generateLayout(mDecor)内部做了什么,从注释6处开始根据不同条件将布局id赋值layoutResource,layoutResource就是最原始的布局,注释7处就会调用mDecor.onResourcesLoaded(mLayoutInflater, layoutResource)将原始布局添加到DecorView。原始布局一般分为三部分,分别是ActionBar,Title和Content,之前看到的mContentParent就是Content这一部分。注释8处可以看到通过findViewById()获得Content布局容器并在最后作为返回值返回。

    <?xml version="1.0" encoding="utf-8"?>
    <!-- Copyright (C) 2006 The Android Open Source Project
    
         Licensed under the Apache License, Version 2.0 (the "License");
         you may not use this file except in compliance with the License.
         You may obtain a copy of the License at
      
              http://www.apache.org/licenses/LICENSE-2.0
      
         Unless required by applicable law or agreed to in writing, software
         distributed under the License is distributed on an "AS IS" BASIS,
         WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
         See the License for the specific language governing permissions and
         limitations under the License.
    -->
    
    <!--
    This is an optimized layout for a screen, with the minimum set of features
    enabled.
    -->
    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:fitsSystemWindows="true">
        <!-- Popout bar for action modes -->
        <ViewStub android:id="@+id/action_mode_bar_stub"
                  android:inflatedId="@+id/action_mode_bar"
                  android:layout="@layout/action_mode_bar"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:theme="?attr/actionBarTheme" />
        <FrameLayout
            android:layout_width="match_parent" 
            android:layout_height="?android:attr/windowTitleSize"
            style="?android:attr/windowTitleBackgroundStyle">
            <TextView android:id="@android:id/title" 
                style="?android:attr/windowTitleStyle"
                android:background="@null"
                android:fadingEdge="horizontal"
                android:gravity="center_vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </FrameLayout>
        <FrameLayout android:id="@android:id/content"
            android:layout_width="match_parent" 
            android:layout_height="0dip"
            android:layout_weight="1"
            android:foregroundGravity="fill_horizontal|top"
            android:foreground="?android:attr/windowContentOverlay" />
    </LinearLayout>
    

    以上是screen_title.xml文件,它是原始布局文件之一,可以看到该文件中由三部分组成,从上到下分别是ActionBar,Title,Content。DecorView对应整个xml文件,也就是说这三部分都在DecorView中。PhoneWindow中的mContentParent对应的是Content这部分,由于Content这部分是FrameLayout布局容器,所以可以添加View。在Activity的onCreate()中调用setContentView()添加布局,最终就是添加在Content这部分的FrameLayout中。

    布局添加成功了,但是此时并没有显示出来,我们都知道在Activity的生命周期中onCreate()用于初始化,onResume()才可见。其实以上说了那么多只是前期准备工作。

    显示视图

    在前面创建视图时说过在调用startActivity()启动一个Activity时,最终会调用到ActivityThread的handleLaunchActivity(),然后创建Activity调用onCreate()方法。

    那么调用onResume()方法是否也有相同之处呢?
    答案是确定的,还是在ActivityThread中,只不过这次调用handleResumeActivity()。

    1.显示Activity
    public final class ActivityThread extends ClientTransactionHandler {
    
        @Override
        public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
                String reason) {
            // If we are getting ready to gc after going to the background, well
            // we are back active so skip it.
            unscheduleGcIdler();
            mSomeActivitiesChanged = true;
    
            // TODO Push resumeArgs into the activity for consideration
            final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason); // 1
            if (r == null) {
                // We didn't actually resume the activity, so skipping any follow-up actions.
                return;
            }
    
          ......
        }
    
        @VisibleForTesting
        public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
                String reason) {
            final ActivityClientRecord r = mActivities.get(token);
            if (localLOGV) {
                Slog.v(TAG, "Performing resume of " + r + " finished=" + r.activity.mFinished);
            }
            if (r == null || r.activity.mFinished) {
                return null;
            }
            if (r.getLifecycleState() == ON_RESUME) {
                if (!finalStateRequest) {
                    final RuntimeException e = new IllegalStateException(
                            "Trying to resume activity which is already resumed");
                    Slog.e(TAG, e.getMessage(), e);
                    Slog.e(TAG, r.getStateString());
                    // TODO(lifecycler): A double resume request is possible when an activity
                    // receives two consequent transactions with relaunch requests and "resumed"
                    // final state requests and the second relaunch is omitted. We still try to
                    // handle two resume requests for the final state. For cases other than this
                    // one, we don't expect it to happen.
                }
                return null;
            }
            if (finalStateRequest) {
                r.hideForNow = false;
                r.activity.mStartedActivity = false;
            }
            try {
                r.activity.onStateNotSaved();
                r.activity.mFragments.noteStateNotSaved();
                checkAndBlockForNetworkAccess();
                if (r.pendingIntents != null) {
                    deliverNewIntents(r, r.pendingIntents);
                    r.pendingIntents = null;
                }
                if (r.pendingResults != null) {
                    deliverResults(r, r.pendingResults, reason);
                    r.pendingResults = null;
                }
                r.activity.performResume(r.startsNotResumed, reason); // 2
    
                r.state = null;
                r.persistentState = null;
                r.setState(ON_RESUME);
            } catch (Exception e) {
                if (!mInstrumentation.onException(r.activity, e)) {
                    throw new RuntimeException("Unable to resume activity "
                            + r.intent.getComponent().toShortString() + ": " + e.toString(), e);
                }
            }
            return r;
        }
    
    }
    

    我们先来看onResume()是何时调用的,在注释1处会调用performResumeActivity(token, finalStateRequest, reason)并返回一个ActivityClientRecord对象。在performResumeActivity()方法中注释2处会调用activity.performResume(r.startsNotResumed, reason)方法。

    public class Activity extends ContextThemeWrapper
            implements LayoutInflater.Factory2,
            Window.Callback, KeyEvent.Callback,
            OnCreateContextMenuListener, ComponentCallbacks2,
            Window.OnWindowDismissedCallback, WindowControllerCallback,
            AutofillManager.AutofillClient {
    
         final void performResume(boolean followedByPause, String reason) {
            performRestart(true /* start */, reason); // 1
    
            mFragments.execPendingActions();
    
            mLastNonConfigurationInstances = null;
    
            if (mAutoFillResetNeeded) {
                // When Activity is destroyed in paused state, and relaunch activity, there will be
                // extra onResume and onPause event,  ignore the first onResume and onPause.
                // see ActivityThread.handleRelaunchActivity()
                mAutoFillIgnoreFirstResumePause = followedByPause;
                if (mAutoFillIgnoreFirstResumePause && DEBUG_LIFECYCLE) {
                    Slog.v(TAG, "autofill will ignore first pause when relaunching " + this);
                }
            }
    
            mCalled = false;
            // mResumed is set by the instrumentation
            mInstrumentation.callActivityOnResume(this); // 2
            
            ......
           
        }
    }
    

    注释1处最终调用了onReStart()和onStart()方法,这里就不详细讲解了,主要看注释2调用了Instrumentation的callActivityOnResume(this),将当前Activity作为参数传入。

    从performResume(boolean followedByPause, String reason) 方法中可以看到先调用注释1处performRestart(true /* start */, reason),在调用注释2处mInstrumentation.callActivityOnResume(this),从而验证了Activity的生命周期onStart()在onResume()之前调用。

    2.调用onResume()
    public class Instrumentation {
    
        public void callActivityOnResume(Activity activity) {
            activity.mResumed = true;
            activity.onResume(); // 1
            
            if (mActivityMonitors != null) {
                synchronized (mSync) {
                    final int N = mActivityMonitors.size();
                    for (int i=0; i<N; i++) {
                        final ActivityMonitor am = mActivityMonitors.get(i);
                        am.match(activity, activity, activity.getIntent());
                    }
                }
            }
        }
    }
    

    从注释1处可以看到callActivityOnResume(activity)方法内部调用了Activity的onResume()方法,此时Activity处于前台可见状态了。

    3.添加DecorView

    现在让我们回到ActivityThread的handleResumeActivity()中。

    public final class ActivityThread extends ClientTransactionHandler {
    
        @Override
        public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
                String reason) {
            // If we are getting ready to gc after going to the background, well
            // we are back active so skip it.
            unscheduleGcIdler();
            mSomeActivitiesChanged = true;
    
            // TODO Push resumeArgs into the activity for consideration
            final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
            if (r == null) {
                // We didn't actually resume the activity, so skipping any follow-up actions.
                return;
            }
    
            final Activity a = r.activity;
    
            if (localLOGV) {
                Slog.v(TAG, "Resume " + r + " started activity: " + a.mStartedActivity
                        + ", hideForNow: " + r.hideForNow + ", finished: " + a.mFinished);
            }
    
            final int forwardBit = isForward
                    ? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
    
            // If the window hasn't yet been added to the window manager,
            // and this guy didn't finish itself or start another activity,
            // then go ahead and add the window.
            boolean willBeVisible = !a.mStartedActivity;
            if (!willBeVisible) {
                try {
                    willBeVisible = ActivityManager.getService().willActivityBeVisible(
                            a.getActivityToken());
                } catch (RemoteException e) {
                    throw e.rethrowFromSystemServer();
                }
            }
            if (r.window == null && !a.mFinished && willBeVisible) {
                r.window = r.activity.getWindow();
                View decor = r.window.getDecorView(); // 1
                decor.setVisibility(View.INVISIBLE);
                ViewManager wm = a.getWindowManager(); // 2
                WindowManager.LayoutParams l = r.window.getAttributes();
                a.mDecor = decor;
                l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
                l.softInputMode |= forwardBit;
                if (r.mPreserveWindow) {
                    a.mWindowAdded = true;
                    r.mPreserveWindow = false;
                    // Normally the ViewRoot sets up callbacks with the Activity
                    // in addView->ViewRootImpl#setView. If we are instead reusing
                    // the decor view we have to notify the view root that the
                    // callbacks may have changed.
                    ViewRootImpl impl = decor.getViewRootImpl();
                    if (impl != null) {
                        impl.notifyChildRebuilt();
                    }
                }
                if (a.mVisibleFromClient) {
                    if (!a.mWindowAdded) {
                        a.mWindowAdded = true;
                        wm.addView(decor, l);  // 3
                    } else {
                        // The activity will get a callback for this {@link LayoutParams} change
                        // earlier. However, at that time the decor will not be set (this is set
                        // in this method), so no action will be taken. This call ensures the
                        // callback occurs with the decor set.
                        a.onWindowAttributesChanged(l);
                    }
                }
    
                // If the window has already been added, but during resume
                // we started another activity, then don't yet make the
                // window visible.
            } else if (!willBeVisible) {
                if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
                r.hideForNow = true;
            }
    
            // Get rid of anything left hanging around.
            cleanUpPendingRemoveWindows(r, false /* force */);
    
            // The window is now visible if it has been added, we are not
            // simply finishing, and we are not starting another activity.
            if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
                if (r.newConfig != null) {
                    performConfigurationChangedForActivity(r, r.newConfig);
                    if (DEBUG_CONFIGURATION) {
                        Slog.v(TAG, "Resuming activity " + r.activityInfo.name + " with newConfig "
                                + r.activity.mCurrentConfig);
                    }
                    r.newConfig = null;
                }
                if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
                WindowManager.LayoutParams l = r.window.getAttributes();
                if ((l.softInputMode
                        & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
                        != forwardBit) {
                    l.softInputMode = (l.softInputMode
                            & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
                            | forwardBit;
                    if (r.activity.mVisibleFromClient) {
                        ViewManager wm = a.getWindowManager();
                        View decor = r.window.getDecorView();
                        wm.updateViewLayout(decor, l);
                    }
                }
    
                r.activity.mVisibleFromServer = true;
                mNumVisibleActivities++;
                if (r.activity.mVisibleFromClient) {
                    r.activity.makeVisible();
                }
            }
    
            r.nextIdle = mNewActivities;
            mNewActivities = r;
            if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
            Looper.myQueue().addIdleHandler(new Idler());
        }
    }
    

    注释1处可以看到拿到了DecorView,注释2处拿到了WindowManager,注释3处调用WindowManager的addView(decor, l)。WindowManger是继承自ViewManager的接口类,ViewManager也是接口类,WindowManagerImpl才是WindowManager的实现类。实则调用WindowManagerImpl的addView(decor, l)方法,并将DecorView作为参数传入。

    public final class WindowManagerImpl implements WindowManager {
    private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
    
        @Override
        public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
            applyDefaultToken(params);
            mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow); // 1
        }
    }
    

    从注释1处可以看到WindowManagerImpl的addView(view,params)又调用了WindowManagerGlobal 的addView(view, params, mContext.getDisplay(), mParentWindow)。

    public final class WindowManagerGlobal {
    
        public void addView(View view, ViewGroup.LayoutParams params,
                Display display, Window parentWindow) {
            if (view == null) {
                throw new IllegalArgumentException("view must not be null");
            }
            if (display == null) {
                throw new IllegalArgumentException("display must not be null");
            }
            if (!(params instanceof WindowManager.LayoutParams)) {
                throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
            }
    
            final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;
            if (parentWindow != null) {
                parentWindow.adjustLayoutParamsForSubWindow(wparams);
            } else {
                // If there's no parent, then hardware acceleration for this view is
                // set from the application's hardware acceleration setting.
                final Context context = view.getContext();
                if (context != null
                        && (context.getApplicationInfo().flags
                                & ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
                    wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
                }
            }
    
            ViewRootImpl root;  // 1
            View panelParentView = null;
    
            synchronized (mLock) {
                // Start watching for system property changes.
                if (mSystemPropertyUpdater == null) {
                    mSystemPropertyUpdater = new Runnable() {
                        @Override public void run() {
                            synchronized (mLock) {
                                for (int i = mRoots.size() - 1; i >= 0; --i) {
                                    mRoots.get(i).loadSystemProperties();
                                }
                            }
                        }
                    };
                    SystemProperties.addChangeCallback(mSystemPropertyUpdater);
                }
    
                int index = findViewLocked(view, false);
                if (index >= 0) {
                    if (mDyingViews.contains(view)) {
                        // Don't wait for MSG_DIE to make it's way through root's queue.
                        mRoots.get(index).doDie();
                    } else {
                        throw new IllegalStateException("View " + view
                                + " has already been added to the window manager.");
                    }
                    // The previous removeView() had not completed executing. Now it has.
                }
    
                // If this is a panel window, then find the window it is being
                // attached to for future reference.
                if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&
                        wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
                    final int count = mViews.size();
                    for (int i = 0; i < count; i++) {
                        if (mRoots.get(i).mWindow.asBinder() == wparams.token) {
                            panelParentView = mViews.get(i);
                        }
                    }
                }
    
                root = new ViewRootImpl(view.getContext(), display); // 2
    
                view.setLayoutParams(wparams);
    
                mViews.add(view);
                mRoots.add(root);
                mParams.add(wparams);
    
                // do this last because it fires off messages to start doing things
                try {
                    root.setView(view, wparams, panelParentView); // 3
                } catch (RuntimeException e) {
                    // BadTokenException or InvalidDisplayException, clean up.
                    if (index >= 0) {
                        removeViewLocked(index, true);
                    }
                    throw e;
                }
            }
        }
    }
    

    注释1处声明了一个ViewRootImpl类型的变量root,ViewRootImpl是ViewParent的实现类,ViewParent是一个接口类。注释2处通过new ViewRootImpl(view.getContext(), display)创建了root,并在注释3处调用了root.setView(view, wparams, panelParentView)。

    public final class ViewRootImpl implements ViewParent,
            View.AttachInfo.Callbacks, ThreadedRenderer.DrawCallbacks {
    
       /**
         * We have one child
         */
        public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
            synchronized (this) {
                if (mView == null) {
                    mView = view;
    
                    ......
              
                    // Schedule the first layout -before- adding to the window
                    // manager, to make sure we do the relayout before receiving
                    // any other events from the system.
                    requestLayout(); // 1
    
                    ......
    
                }
            }
        }
    
        @Override
        public void requestLayout() {
            if (!mHandlingLayoutInLayoutRequest) {
                checkThread();
                mLayoutRequested = true;
                scheduleTraversals(); // 2
            }
        }
    
        void scheduleTraversals() {
            if (!mTraversalScheduled) {
                mTraversalScheduled = true;
                mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
                mChoreographer.postCallback(
                        Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null); // 3
                if (!mUnbufferedInputDispatch) {
                    scheduleConsumeBatchedInput();
                }
                notifyRendererOfFramePending();
                pokeDrawLockIfNeeded();
            }
        }
    
        final class TraversalRunnable implements Runnable {
            @Override
            public void run() {
                doTraversal(); // 4
            }
        }
        final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
    
        void doTraversal() {
            if (mTraversalScheduled) {
                mTraversalScheduled = false;
                mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
    
                if (mProfile) {
                    Debug.startMethodTracing("ViewAncestor");
                }
    
                performTraversals(); // 5
    
                if (mProfile) {
                    Debug.stopMethodTracing();
                    mProfile = false;
                }
            }
        }
    
       private void performTraversals() {
            
            ......
    
            final boolean isViewVisible = viewVisibility == View.VISIBLE;
            final boolean windowRelayoutWasForced = mForceNextWindowRelayout;
            if (mFirst || windowShouldResize || insetsChanged ||
                    viewVisibilityChanged || params != null || mForceNextWindowRelayout) {
    
                    ......
    
                    if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
                            || mHeight != host.getMeasuredHeight() || contentInsetsChanged ||
                            updatedConfiguration) {
                        int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width); // 6
                        int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height); // 7
    
                        if (DEBUG_LAYOUT) Log.v(mTag, "Ooops, something changed!  mWidth="
                                + mWidth + " measuredWidth=" + host.getMeasuredWidth()
                                + " mHeight=" + mHeight
                                + " measuredHeight=" + host.getMeasuredHeight()
                                + " coveredInsetsChanged=" + contentInsetsChanged);
    
                         // Ask host how big it wants to be
                        performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); // 8
    
                        // Implementation of weights from WindowManager.LayoutParams
                        // We just grow the dimensions as needed and re-measure if
                        // needs be
                        int width = host.getMeasuredWidth();
                        int height = host.getMeasuredHeight();
                        boolean measureAgain = false;
    
                        if (lp.horizontalWeight > 0.0f) {
                            width += (int) ((mWidth - width) * lp.horizontalWeight);
                            childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
                                    MeasureSpec.EXACTLY);
                            measureAgain = true;
                        }
                        if (lp.verticalWeight > 0.0f) {
                            height += (int) ((mHeight - height) * lp.verticalWeight);
                            childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
                                    MeasureSpec.EXACTLY);
                            measureAgain = true;
                        }
    
                        if (measureAgain) {
                            if (DEBUG_LAYOUT) Log.v(mTag,
                                    "And hey let's measure once more: width=" + width
                                    + " height=" + height);
                            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
                        }
    
                        layoutRequested = true;
                    }
                }
            } else {
                // Not the first pass and no window/insets/visibility change but the window
                // may have moved and we need check that and if so to update the left and right
                // in the attach info. We translate only the window frame since on window move
                // the window manager tells us only for the new frame but the insets are the
                // same and we do not want to translate them more than once.
                maybeHandleWindowMove(frame);
            }
    
            final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw);
            boolean triggerGlobalLayoutListener = didLayout
                    || mAttachInfo.mRecomputeGlobalAttributes;
            if (didLayout) {
                performLayout(lp, mWidth, mHeight); // 9
    
                // By this point all views have been sized and positioned
                // We can compute the transparent area
    
                if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
                    // start out transparent
                    // TODO: AVOID THAT CALL BY CACHING THE RESULT?
                    host.getLocationInWindow(mTmpLocation);
                    mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
                            mTmpLocation[0] + host.mRight - host.mLeft,
                            mTmpLocation[1] + host.mBottom - host.mTop);
    
                    host.gatherTransparentRegion(mTransparentRegion);
                    if (mTranslator != null) {
                        mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
                    }
    
                    if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
                        mPreviousTransparentRegion.set(mTransparentRegion);
                        mFullRedrawNeeded = true;
                        // reconfigure window manager
                        try {
                            mWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
                        } catch (RemoteException e) {
                        }
                    }
                }
    
                if (DBG) {
                    System.out.println("======================================");
                    System.out.println("performTraversals -- after setFrame");
                    host.debug();
                }
            }
    
            if (triggerGlobalLayoutListener) {
                mAttachInfo.mRecomputeGlobalAttributes = false;
                mAttachInfo.mTreeObserver.dispatchOnGlobalLayout();
            }
    
            if (computesInternalInsets) {
                // Clear the original insets.
                final ViewTreeObserver.InternalInsetsInfo insets = mAttachInfo.mGivenInternalInsets;
                insets.reset();
    
                // Compute new insets in place.
                mAttachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
                mAttachInfo.mHasNonEmptyGivenInternalInsets = !insets.isEmpty();
    
                // Tell the window manager.
                if (insetsPending || !mLastGivenInsets.equals(insets)) {
                    mLastGivenInsets.set(insets);
    
                    // Translate insets to screen coordinates if needed.
                    final Rect contentInsets;
                    final Rect visibleInsets;
                    final Region touchableRegion;
                    if (mTranslator != null) {
                        contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
                        visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
                        touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
                    } else {
                        contentInsets = insets.contentInsets;
                        visibleInsets = insets.visibleInsets;
                        touchableRegion = insets.touchableRegion;
                    }
    
                    try {
                        mWindowSession.setInsets(mWindow, insets.mTouchableInsets,
                                contentInsets, visibleInsets, touchableRegion);
                    } catch (RemoteException e) {
                    }
                }
            }
    
            if (mFirst) {
                if (sAlwaysAssignFocus || !isInTouchMode()) {
                    // handle first focus request
                    if (DEBUG_INPUT_RESIZE) {
                        Log.v(mTag, "First: mView.hasFocus()=" + mView.hasFocus());
                    }
                    if (mView != null) {
                        if (!mView.hasFocus()) {
                            mView.restoreDefaultFocus();
                            if (DEBUG_INPUT_RESIZE) {
                                Log.v(mTag, "First: requested focused view=" + mView.findFocus());
                            }
                        } else {
                            if (DEBUG_INPUT_RESIZE) {
                                Log.v(mTag, "First: existing focused view=" + mView.findFocus());
                            }
                        }
                    }
                } else {
                    // Some views (like ScrollView) won't hand focus to descendants that aren't within
                    // their viewport. Before layout, there's a good change these views are size 0
                    // which means no children can get focus. After layout, this view now has size, but
                    // is not guaranteed to hand-off focus to a focusable child (specifically, the edge-
                    // case where the child has a size prior to layout and thus won't trigger
                    // focusableViewAvailable).
                    View focused = mView.findFocus();
                    if (focused instanceof ViewGroup
                            && ((ViewGroup) focused).getDescendantFocusability()
                                    == ViewGroup.FOCUS_AFTER_DESCENDANTS) {
                        focused.restoreDefaultFocus();
                    }
                }
            }
    
            final boolean changedVisibility = (viewVisibilityChanged || mFirst) && isViewVisible;
            final boolean hasWindowFocus = mAttachInfo.mHasWindowFocus && isViewVisible;
            final boolean regainedFocus = hasWindowFocus && mLostWindowFocus;
            if (regainedFocus) {
                mLostWindowFocus = false;
            } else if (!hasWindowFocus && mHadWindowFocus) {
                mLostWindowFocus = true;
            }
    
            if (changedVisibility || regainedFocus) {
                // Toasts are presented as notifications - don't present them as windows as well
                boolean isToast = (mWindowAttributes == null) ? false
                        : (mWindowAttributes.type == WindowManager.LayoutParams.TYPE_TOAST);
                if (!isToast) {
                    host.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
                }
            }
    
            mFirst = false;
            mWillDrawSoon = false;
            mNewSurfaceNeeded = false;
            mActivityRelaunched = false;
            mViewVisibility = viewVisibility;
            mHadWindowFocus = hasWindowFocus;
    
            if (hasWindowFocus && !isInLocalFocusMode()) {
                final boolean imTarget = WindowManager.LayoutParams
                        .mayUseInputMethod(mWindowAttributes.flags);
                if (imTarget != mLastWasImTarget) {
                    mLastWasImTarget = imTarget;
                    InputMethodManager imm = InputMethodManager.peekInstance();
                    if (imm != null && imTarget) {
                        imm.onPreWindowFocus(mView, hasWindowFocus);
                        imm.onPostWindowFocus(mView, mView.findFocus(),
                                mWindowAttributes.softInputMode,
                                !mHasHadWindowFocus, mWindowAttributes.flags);
                    }
                }
            }
    
            // Remember if we must report the next draw.
            if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
                reportNextDraw();
            }
    
            boolean cancelDraw = mAttachInfo.mTreeObserver.dispatchOnPreDraw() || !isViewVisible;
    
            if (!cancelDraw && !newSurface) {
                if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
                    for (int i = 0; i < mPendingTransitions.size(); ++i) {
                        mPendingTransitions.get(i).startChangingAnimations();
                    }
                    mPendingTransitions.clear();
                }
    
                performDraw(); // 10
            } else {
                if (isViewVisible) {
                    // Try again
                    scheduleTraversals();
                } else if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
                    for (int i = 0; i < mPendingTransitions.size(); ++i) {
                        mPendingTransitions.get(i).endChangingAnimations();
                    }
                    mPendingTransitions.clear();
                }
            }
    
            mIsInTraversal = false;
        }
    
    }
    

    这一段代码有点长,让我们耐心看完,首先看setView()方法内部注释1处调用了requestLayout()方法,在requestLayout()方法内部注释2处调用了scheduleTraversals()方法,在scheduleTraversals()方法内部注释3处通过Choreographer.postCallback(
    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null),在TraversalRunnable的run()方法内部注释4处调用了doTraversal()方法,在doTraversal()方法内部注释5处调用了performTraversals()方法,在performTraversals()方法内部注释6,7处计算出了宽和高的MesureSpec,并在注释8处调用performMeasure(childWidthMeasureSpec, childHeightMeasureSpec)作为参数传入,接着又调用了注释9处的performLayout(lp, mWidth, mHeight)和注释10处的perrformDraw()。

    调用流程:setView() >>> requestLayout() >>> scheduleTraversals() >>>
    Choreographer.postCallback() >>> doTraversal() >>> performTraversals() >>> performMeasure()/performLayout()/performDraw()

    public final class ViewRootImpl implements ViewParent,
            View.AttachInfo.Callbacks, ThreadedRenderer.DrawCallbacks {
    
        private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
            if (mView == null) {
                return;
            }
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
            try {
                mView.measure(childWidthMeasureSpec, childHeightMeasureSpec); // 1
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }
        }
    
        private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
                int desiredWindowHeight) {
            mLayoutRequested = false;
            mScrollMayChange = true;
            mInLayout = true;
    
            final View host = mView;
            if (host == null) {
                return;
            }
            if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {
                Log.v(mTag, "Laying out " + host + " to (" +
                        host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
            }
    
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
            try {
                host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight()); // 2
    
                mInLayout = false;
                int numViewsRequestingLayout = mLayoutRequesters.size();
                if (numViewsRequestingLayout > 0) {
                    // requestLayout() was called during layout.
                    // If no layout-request flags are set on the requesting views, there is no problem.
                    // If some requests are still pending, then we need to clear those flags and do
                    // a full request/measure/layout pass to handle this situation.
                    ArrayList<View> validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters,
                            false);
                    if (validLayoutRequesters != null) {
                        // Set this flag to indicate that any further requests are happening during
                        // the second pass, which may result in posting those requests to the next
                        // frame instead
                        mHandlingLayoutInLayoutRequest = true;
    
                        // Process fresh layout requests, then measure and layout
                        int numValidRequests = validLayoutRequesters.size();
                        for (int i = 0; i < numValidRequests; ++i) {
                            final View view = validLayoutRequesters.get(i);
                            Log.w("View", "requestLayout() improperly called by " + view +
                                    " during layout: running second layout pass");
                            view.requestLayout();
                        }
                        measureHierarchy(host, lp, mView.getContext().getResources(),
                                desiredWindowWidth, desiredWindowHeight);
                        mInLayout = true;
                        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
    
                        mHandlingLayoutInLayoutRequest = false;
    
                        // Check the valid requests again, this time without checking/clearing the
                        // layout flags, since requests happening during the second pass get noop'd
                        validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, true);
                        if (validLayoutRequesters != null) {
                            final ArrayList<View> finalRequesters = validLayoutRequesters;
                            // Post second-pass requests to the next frame
                            getRunQueue().post(new Runnable() {
                                @Override
                                public void run() {
                                    int numValidRequests = finalRequesters.size();
                                    for (int i = 0; i < numValidRequests; ++i) {
                                        final View view = finalRequesters.get(i);
                                        Log.w("View", "requestLayout() improperly called by " + view +
                                                " during second layout pass: posting in next frame");
                                        view.requestLayout();
                                    }
                                }
                            });
                        }
                    }
    
                }
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }
            mInLayout = false;
        }
    
       private void performDraw() {
            if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) {
                return;
            } else if (mView == null) {
                return;
            }
    
            final boolean fullRedrawNeeded = mFullRedrawNeeded || mReportNextDraw;
            mFullRedrawNeeded = false;
    
            mIsDrawing = true;
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
    
            boolean usingAsyncReport = false;
            if (mReportNextDraw && mAttachInfo.mThreadedRenderer != null
                    && mAttachInfo.mThreadedRenderer.isEnabled()) {
                usingAsyncReport = true;
                mAttachInfo.mThreadedRenderer.setFrameCompleteCallback((long frameNr) -> {
                    // TODO: Use the frame number
                    pendingDrawFinished();
                });
            }
    
            try {
                boolean canUseAsync = draw(fullRedrawNeeded); // 3
                if (usingAsyncReport && !canUseAsync) {
                    mAttachInfo.mThreadedRenderer.setFrameCompleteCallback(null);
                    usingAsyncReport = false;
                }
            } finally {
                mIsDrawing = false;
                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }
    
            // For whatever reason we didn't create a HardwareRenderer, end any
            // hardware animations that are now dangling
            if (mAttachInfo.mPendingAnimatingRenderNodes != null) {
                final int count = mAttachInfo.mPendingAnimatingRenderNodes.size();
                for (int i = 0; i < count; i++) {
                    mAttachInfo.mPendingAnimatingRenderNodes.get(i).endAllAnimators();
                }
                mAttachInfo.mPendingAnimatingRenderNodes.clear();
            }
    
            if (mReportNextDraw) {
                mReportNextDraw = false;
    
                // if we're using multi-thread renderer, wait for the window frame draws
                if (mWindowDrawCountDown != null) {
                    try {
                        mWindowDrawCountDown.await();
                    } catch (InterruptedException e) {
                        Log.e(mTag, "Window redraw count down interrupted!");
                    }
                    mWindowDrawCountDown = null;
                }
    
                if (mAttachInfo.mThreadedRenderer != null) {
                    mAttachInfo.mThreadedRenderer.setStopped(mStopped);
                }
    
                if (LOCAL_LOGV) {
                    Log.v(mTag, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
                }
    
                if (mSurfaceHolder != null && mSurface.isValid()) {
                    SurfaceCallbackHelper sch = new SurfaceCallbackHelper(this::postDrawFinished);
                    SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
    
                    sch.dispatchSurfaceRedrawNeededAsync(mSurfaceHolder, callbacks);
                } else if (!usingAsyncReport) {
                    if (mAttachInfo.mThreadedRenderer != null) {
                        mAttachInfo.mThreadedRenderer.fence();
                    }
                    pendingDrawFinished();
                }
            }
        }
    }
    

    performTraversals()方法中会依次调用performMeasure(),performLayout()和performDraw()进行测量,布局和绘制。其中performMeasure()和performLayout()方法内部会直接调用View的measure()和layout()方法,而performDraw()则不同。performDraw()会调用draw(fullRedrawNeeded),draw(fullRedrawNeeded)内部会调用mAttachInfo.mThreadedRenderer.draw(mView, mAttachInfo, this, callback),ThreadedRenderer.draw(mView, mAttachInfo, this, callback)内部还会调用ThreadedRenderer.updateRootDisplayList(view, callbacks),ThreadedRenderer.updateRootDisplayList(view, callbacks)内部还会调用ThreadedRenderer.updateViewTreeDisplayList(view),ThreadedRenderer.updateViewTreeDisplayList(view)内部还会调用View.updateDisplayListIfDirty(),View.updateDisplayListIfDirty()内部才会调用View.draw(Canvas)。

    绘制流程:ViewRootImpl.performDraw() >>> ViewRootImpl.draw(fullRedrawNeeded) >>> ThreadedRenderer.draw(mView, mAttachInfo, this, callback) >>> ThreadedRenderer.updateRootDisplayList(view, callbacks) >>> ThreadedRenderer.updateViewTreeDisplayList(view) >>> View.updateDisplayListIfDirty() >>> View.draw(Canvas)

    总结

    ActivityThread.handleLaunchActivity()最终会调用Activity.onCreate()。
    ActivityThread.handleResumeActiviy()最终会调用Activity.onRestart(),onStart(),onResume()。

    ActivityThread.handleLaunchActivity()会调用ActivityThread.performLaunchActivity()创建Activity并调用Activity.attch()初始化PhoneWindow,WindowManager等常量做准备工作。

    Activity.onCreate()中调用Activity.setContentView()添加布局,ActivityThread.handleResumeActivity()才会真正去添加布局到Window并最终在ViewRootImpl调用performTraversals()遍历View树,此时界面才会显示出来。

    绘制流程.png

    相关文章

      网友评论

        本文标题:View的绘制流程

        本文链接:https://www.haomeiwen.com/subject/jzhjrctx.html