View的绘制流程

Activity所有的生命周期方法调用都是在ActivityThread类中执行的。

比如ActivityonCreate生命周期:

 @Override
    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
        final Activity a = performLaunchActivity(r, customIntent);
        return a;
    }
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
  Activity activity = null;
  //通过反射得到activity对象。
  java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
  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,
                        r.assistToken);
  if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
  return activity;
    }

最后在Instrumentation类中执行callActivityOnCreate方法,callActivityOnCreate方法中,执行Activity中的performCreate方法,最后执行onCreate方法。
可以在ActivityThread中找到Activity其他生命周期方法:

  • handleStartActivity
  • handleResumeActivity
  • handlePauseActivity
    等等。

Activity的onCreate

启动Activity首先执行onCreate方法,也就是刚刚performLaunchActivity方法,在performLaunchActivity方法中,在执行callActivityOnCreate之前也就是执行ActivityonCreate方法之前先执行了Activityattach()方法。

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, IBinder assistToken) {
        mWindow = new PhoneWindow(this, window, activityConfigCallback);
        mWindow.setWindowControllerCallback(this);
        mWindow.setCallback(this);
        mWindow.setOnWindowDismissedCallback(this);
        mWindow.getLayoutInflater().setPrivateFactory(this);
        if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
            mWindow.setSoftInputMode(info.softInputMode);
        }
        if (info.uiOptions != 0) {
            mWindow.setUiOptions(info.uiOptions);
        }
        mWindow.setWindowManager(
                (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
                mToken, mComponent.flattenToString(),
                (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
        if (mParent != null) {
            mWindow.setContainer(mParent.getWindow());
        }
        mWindowManager = mWindow.getWindowManager();
        mCurrentConfig = config;
        mWindow.setColorMode(info.colorMode);
        setAutofillOptions(application.getAutofillOptions());
    }

attach方法中创建了PhoneWindow,并执行了setWindowManager方法,

public void setWindowManager(WindowManager wm, IBinder appToken, String appName,
            boolean hardwareAccelerated) {
        mAppToken = appToken;
        mAppName = appName;
        mHardwareAccelerated = hardwareAccelerated;
        if (wm == null) {
            wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
        }
        mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);
    }

mWindowPhoneWindow
这个方法设置的是WindowManagerImpl类。

记住这一点
-- 海绵宝宝

setContentView()

Activity方法中执行setContentView方法

public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }

海绵宝宝上面说getWindow就是PhoneWindow,
所以就是调用PhoneWindowsetContentView方法:

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();
        } 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);
        }

最后一行,是将传入的布局id加载到mContentParent中,在第一行中,首先会判断mContentParent是否是空,如果是null进入到installDecor方法中,先看一下这个方法都在做什么操作:

private void installDecor() {
  if (mDecor == null) {
            mDecor = generateDecor(-1);
            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);
  }
}

上面方法会创建一个DecorViewmContentParent
进入到generateLayout方法中:

protected ViewGroup generateLayout(DecorView decor) {
  int layoutResource;
  layoutResource = R.layout.screen_simple;
  mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
  ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
  return contentParent;
}

layoutResource 布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">
    <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:id="@android:id/content"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:foregroundInsidePadding="false"
         android:foregroundGravity="fill_horizontal|top"
         android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>

执行DecorViewonResourcesLoaded方法:

void onResourcesLoaded(LayoutInflater inflater, int layoutResource) {
  final View root = inflater.inflate(layoutResource, null);
  if (mDecorCaptionView != null) {
            if (mDecorCaptionView.getParent() == null) {
                addView(mDecorCaptionView,
                        new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
            }
            mDecorCaptionView.addView(root,
                    new ViewGroup.MarginLayoutParams(MATCH_PARENT, MATCH_PARENT));
        } else {

            // Put it below the color views.
            addView(root, 0, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
        }
}

根据布局id,将View添加到DecorView中。

 ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);

这个就是我们布局当中的FrameLayout
这样我们就把我们的布局View添加到了系统的FrameLayout中。

总结:

ActivityThreadhandleLaunchAcitivity方法进入到performLaunchActivity方法,performLaunchActivity方法进行实例化Activity,并执行Activityattach方法和onCreate方法,其中attach方法实例化了PhoneWindow,和设置了WindowManagerImpl
执行完attach方法之后执行onCreate方法中的setContentView方法,调用PhoneWindowsetContentView方法,在setContentView方法中,实例化了DecorView和然后将我们的系统布局添加到了DecorView中,然后根据id找到FrameLayout,最后将用户的布局文件放到FrameLayout中

流程图

结构图

等等好像没有ViewRootImpl什么关系:

ActivityThreadhandleResumeActivity方法:

public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
            String reason) {
  final Activity a = r.activity;
  r.window = r.activity.getWindow();
  View decor = r.window.getDecorView();
  decor.setVisibility(View.INVISIBLE);
  ViewManager wm = a.getWindowManager();
  WindowManager.LayoutParams l = r.window.getAttributes();
  a.mDecor = decor;
  l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
  l.softInputMode |= forwardBit;
  if (a.mVisibleFromClient) {
      if (!a.mWindowAdded) {
           a.mWindowAdded = true;
           wm.addView(decor, l);
       } 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);
        }
     }
}

最后执行wm.addView(decor, l),海绵宝宝说这个是wmWindowManagerImpl类,decor就是DecorView,进入WindowManagerImpladdView方法:

public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
        applyDefaultToken(params);
        mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
    }

WindowMangerImpl调用WindowManagerGlobaladdView方法:

public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
  ViewRootImpl root;
  synchronized (mLock) {
  root = new ViewRootImpl(view.getContext(), display);

  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);
  } catch (RuntimeException e) {
    // BadTokenException or InvalidDisplayException, clean up.
     if (index >= 0) {
         removeViewLocked(index, true);
      }
       throw e;
    }
  }
}

在此方法中会实例化ViewRootImpl,并将decorView传入到ViewRootIpmlsetView方法中。

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
  //view就是decorview
  mView = view;
  requestLayout();
  //设置decorview的父布局为viewrootImpl
  view.assignParent(this);
}

在设置decorview的父布局为viewrootImpl之前执行requestLayout方法:

@Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }

在此方法里面会做检查线程的操作然后执行scheduleTraversals():

void scheduleTraversals() {
  mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
}
final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }
    final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
void doTraversal() {
        if (mTraversalScheduled) {
            mTraversalScheduled = false;
            mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);

            if (mProfile) {
                Debug.startMethodTracing("ViewAncestor");
            }

            performTraversals();

            if (mProfile) {
                Debug.stopMethodTracing();
                mProfile = false;
            }
        }
    }

最后在performTraversals方法里面会执行DecorView的测量布局和绘制。

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