關於View中mParent的來龍去脈

-l囧l-發表於2019-03-01

以下程式碼來自android-26

mParent賦值

View#assignParent

void assignParent(ViewParent parent) {
        if (mParent == null) {
            mParent = parent;
        } else if (parent == null) {
            mParent = null;
        } else {
            throw new RuntimeException("view " + this + " being added, but"
                    + " it already has a parent");
        }
    }複製程式碼

下面的分析我們會分三部分來分析,第一部分是DecorView的由來,第二部分是DecorView的mParent,而第三部分是普通view(DecorView的子view)的mParent。

首先我們看下View#assignParent都在哪些地方被呼叫了,方便我們在原始碼的海洋中不至於迷失。

image.png
image.png

DecorView的由來

首先我們得知道assignParent是在什麼地方被呼叫的。其實是在ViewRootImpl#setView中被呼叫的。接下來我們一步步分析。我們知道只有startActivity()開啟一個新的activity的時候頁面才會被渲染。而startActivity會一步步呼叫到ActivityThread#performLaunchActivity方法。

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");

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

                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;
                //注意下面的程式碼 這是activity生命週期開始的地方
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                if (!activity.mCalled) {
                    throw new SuperNotCalledException(
                        "Activity " + r.intent.getComponent().toShortString() +
                        " did not call through to super.onCreate()");
                }
                r.activity = activity;
                r.stopped = true;
                if (!r.activity.mFinished) {
                    activity.performStart();
                    r.stopped = false;
                }
                if (!r.activity.mFinished) {
                    if (r.isPersistable()) {
                        if (r.state != null || r.persistentState != null) {
                            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                                    r.persistentState);
                        }
                    } else if (r.state != null) {
                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                    }
                }
                if (!r.activity.mFinished) {
                    activity.mCalled = false;
                    if (r.isPersistable()) {
                        mInstrumentation.callActivityOnPostCreate(activity, r.state,
                                r.persistentState);
                    } else {
                        mInstrumentation.callActivityOnPostCreate(activity, r.state);
                    }
                    if (!activity.mCalled) {
                        throw new SuperNotCalledException(
                            "Activity " + r.intent.getComponent().toShortString() +
                            " did not call through to super.onPostCreate()");
                    }
                }
            }
            r.paused = true;

            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;
    }複製程式碼

我們看到呼叫了mInstrumentation.callActivityOnCreate(activity, r.state);;

Instrumentation#callActivityOnCreate&Activity#performCreate

public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        activity.performCreate(icicle);
        postPerformCreate(activity);
    }

Activity#performCreate

final void performCreate(Bundle icicle) {
        restoreHasCurrentPermissionRequest(icicle);
        onCreate(icicle);
        mActivityTransitionState.readState(icicle);
        performCreateCommon();
    }複製程式碼

我們一般都會在onCreate()方法中呼叫setContentView方法

Activity#setContentView

public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }複製程式碼

image.png
image.png

而getWindow其實是PhoneWindow,PhoneWindow其實是屬於核心程式碼,不屬於app程式,我們進去看看。

PhoneWindow#setContentView

@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) {
            //進行了DecorView的初始化
            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);
        }
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
        mContentParentExplicitlySet = true;
    }複製程式碼

到這為止我們已經知道了DecorView是在PhoneWindow#setContentView被賦值的,而PhoneWindow#setContentView又是通過Activity#setContentView一步步呼叫得到的。

20160323161350830.png
20160323161350830.png

DecorView.mParent的真相

下面我們換個思路,大家如果去看過我的從startActivity一步步到穿越程式壁壘就會知道,當呼叫startActivity的時候會進行跨程式呼叫,最終會呼叫到ApplicationThread#scheduleLaunchActivity,而ApplicationThread是ActivityThread的內部類。

ApplicationThread#scheduleLaunchActivity

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
         ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
         CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
         int procState, Bundle state, PersistableBundle persistentState,
         List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
         boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {

     updateProcessState(procState, false);

     ActivityClientRecord r = new ActivityClientRecord();

     r.token = token;
     r.ident = ident;
     r.intent = intent;
     r.referrer = referrer;
     r.voiceInteractor = voiceInteractor;
     r.activityInfo = info;
     r.compatInfo = compatInfo;
     r.state = state;
     r.persistentState = persistentState;

     r.pendingResults = pendingResults;
     r.pendingIntents = pendingNewIntents;

     r.startsNotResumed = notResumed;
     r.isForward = isForward;

     r.profilerInfo = profilerInfo;

     r.overrideConfig = overrideConfig;
     updatePendingConfiguration(curConfig);
     //注意這行程式碼
     sendMessage(H.LAUNCH_ACTIVITY, r);
 }複製程式碼

可以看到sendMessage會切換到UI執行緒繼續進行有關UI的操作,而程式碼會進入到ActivityThread的內部類H extends Handler 。

ActivityThread#H#handleMessage

public void handleMessage(Message msg) {
switch (msg.what) {
                case LAUNCH_ACTIVITY: {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                    final ActivityClientRecord r = (ActivityClientRecord) msg.obj;

                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } break;
            ……
        }
}複製程式碼

ActivityThread#handleLaunchActivity

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
      ……
        // Initialize before creating the activity
        WindowManagerGlobal.initialize();
        //在上文中我們知道performLaunchActivity最終會的初始化DecorView
        Activity a = performLaunchActivity(r, customIntent);
        ……
        handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
        ……
    }複製程式碼

ActivityThread#handleResumeActivity

final void handleResumeActivity(IBinder token,
            boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
          ……
        r = performResumeActivity(token, clearHide, reason);
        ……
        if (r.window == null && !a.mFinished && willBeVisible) {
                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 (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;
                        //注意這行程式碼將DecorView關聯到WindowManager,而WindowManager是一個介面,真正的實現是WindowManagerImpl
                        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);
                    }
                }

            // If the window has already been added, but during resume
            // we started another activity, then don't yet make the
            // window visible.
            }
}複製程式碼

通過註釋我們知道WindowManagerImpl會將DecorView
一般每一個handleXXX方法中都會呼叫一個對應的performXXX方法,內部會呼叫到到呼叫到activity的resume生命週期,我們這裡不進行探究了。

WindowManagerImpl#addView&WindowManagerGlobal#addView

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


WindowManagerGlobal#addView

public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
         ……
      public void addView(View view, ViewGroup.LayoutParams params,Display display, Window parentWindow) {
         ViewRootImpl root;
         synchronized (mLock) {
            //我們new了一個ViewRootImpl當做root
            root = new ViewRootImpl(view.getContext(), display);
            view.setLayoutParams(wparams);
            mViews.add(view);
            mRoots.add(root);
            mParams.add(wparams);
        try {
            //注意這行程式碼
            root.setView(view, wparams, panelParentView);
        } catch (RuntimeException e) {
            // BadTokenException or InvalidDisplayException, clean up.
            synchronized (mLock) {
                final int index = findViewLocked(view, false);
                if (index >= 0) {
                    removeViewLocked(index, true);
                }
            }
            throw e;
        }
      }
   }複製程式碼

首先我們看下ViewRootImpl是什麼。

image.png
image.png

ViewRootImpl繼承了ViewParent,然後我們來看下ViewParent家族。
image.png
image.png

這裡顯示他的另一個子類是ViewGroup。這裡我們只要知道就行了,下面我會說為什麼要檢視ViewParent家族。

我們看下ViewRootImpl#setView,程式碼比較長,我們只最追重要的看。

ViewRootImpl#setView

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
        synchronized (this) {
            if (mView == null) {
                mView = view;
                //注意這行程式碼
                view.assignParent(this);
                ……
            }
        }
    }複製程式碼

通過註釋我們可以看到view.assignParent(this),而這個View就是我們上文的DecorView。至此,我們終於知道了DecorView.mParent其實就是ViewRootImpl。

子View.mParent的真相

我們費了千辛萬苦知道了DecorView.mParent是ViewRootImpl,那麼DecorView的直接子view的mParent你說應當就應該是DecorView,然後一級一級巢狀著。不過這只是我們的猜想,我們還需要驗證,怎麼驗證,當然是再去原始碼中查詢咯。從上文中我們知道assignParent的呼叫鏈出現在了ViewGroup#addViewInner中。

ViewGroup#addViewInner

image.png
image.png

image.png
image.png

多麼的簡單明瞭啊,直接把自己賦值給了子View。所以在這裡我們可以直接下結論了,子View.mParent是他的父View(廢話,從名字就能看出來了好嗎)。

總結

每分析一次原始碼都會使自己更接近真相,希望大家也能自己一步步去跟一遍。 下一篇打算分析哪個模組的程式碼,暫時還沒有想好,大家如果有好的建議的話,可以給我留言。好了,拜了個拜。大吉大利,晚上吃雞!!!!

相關文章