一年多之前,曾經覺得本身對 View 的添加顯示邏輯已經有所瞭解了,過後發現也只是懂了些皮毛而已。通過一年多的實戰,Android 和 Java 基礎都有了提高,是時候該去看看 DecorView 的添加顯示。android
Android 中 Activity 是做爲應用程序的載體存在,表明着一個完整的用戶界面,提供了一個窗口來繪製各類視圖,當 Activity 啓動時,咱們會經過 setContentView 方法來設置一個內容視圖,這個內容視圖就是用戶看到的界面。那麼 View 和 activity 是如何關聯在一塊兒的呢 ?app
上圖是 View 和 Activity 之間的關係。先解釋圖中一些類的做用以及相關關係:異步
Activity : 對於每個 activity 都會有擁有一個 PhoneWindow。ide
DecorView 是一個應用窗口的根容器,它本質上是一個 FrameLayout。DecorView 有惟一一個子 View,它是一個垂直 LinearLayout,包含兩個子元素,一個是 TitleView( ActionBar 的容器),另外一個是 ContentView(窗口內容的容器)。oop
ContentView :是一個 FrameLayout(android.R.id.content),咱們日常用的 setContentView 就是設置它的子 View 。佈局
ViewRootImpl :擁有 DecorView 的實例,經過該實例來控制 DecorView 繪製。ViewRootImpl 的一個內部類 W,實現了 IWindow 接口,IWindow 接口是供 WMS 使用的,WSM 經過調用 IWindow 一些方法,經過 Binder 通訊的方式,最後執行到了 W 中對應的方法中。一樣的,ViewRootImpl 經過 IWindowSession 來調用 WMS 的 Session 一些方法。Session 類繼承自 IWindowSession.Stub
,每個應用進程都有一個惟一的 Session 對象與 WMS 通訊。post
先從 Mainactivity 中的代碼看起,首先是調用了 setContentView;動畫
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }
該方法是父類 AppCompatActivity 的方法,最終會調用 AppCompatDelegateImpl 的 setContentView 方法:this
// AppCompatDelegateImpl
public void setContentView(int resId) { this.ensureSubDecor(); ViewGroup contentParent = (ViewGroup)this.mSubDecor.findViewById(16908290); contentParent.removeAllViews(); LayoutInflater.from(this.mContext).inflate(resId, contentParent); this.mOriginalWindowCallback.onContentChanged(); }
ensureSubDecor 從字面理解就是建立 subDecorView,這個是根據主題來建立的,下文也會講到。建立完之後,從中獲取 contentParent,再將從 activity 傳入的 id xml 佈局添加到裏面。不過你們注意的是,在添加以前先調用 removeAllViews() 方法,確保沒有其餘子 View 的干擾。spa
private void ensureSubDecor() { if (!this.mSubDecorInstalled) { this.mSubDecor = this.createSubDecor(); ...... } ...... }
最終會調用 createSubDecor() ,來看看裏面的具體代碼邏輯:
private ViewGroup createSubDecor() { // 一、獲取主題參數,進行一些設置,包括標題,actionbar 等 TypedArray a = this.mContext.obtainStyledAttributes(styleable.AppCompatTheme); if (!a.hasValue(styleable.AppCompatTheme_windowActionBar)) { a.recycle(); throw new IllegalStateException("You need to use a Theme.AppCompat theme (or descendant) with this activity."); } else { if (a.getBoolean(styleable.AppCompatTheme_windowNoTitle, false)) { this.requestWindowFeature(1); } else if (a.getBoolean(styleable.AppCompatTheme_windowActionBar, false)) { this.requestWindowFeature(108); } if (a.getBoolean(styleable.AppCompatTheme_windowActionBarOverlay, false)) { this.requestWindowFeature(109); } if (a.getBoolean(styleable.AppCompatTheme_windowActionModeOverlay, false)) { this.requestWindowFeature(10); } this.mIsFloating = a.getBoolean(styleable.AppCompatTheme_android_windowIsFloating, false); a.recycle(); // 二、確保優先初始化 DecorView this.mWindow.getDecorView(); LayoutInflater inflater = LayoutInflater.from(this.mContext); ViewGroup subDecor = null; // 三、根據不一樣的設置來對 subDecor 進行初始化 if (!this.mWindowNoTitle) { if (this.mIsFloating) { subDecor = (ViewGroup)inflater.inflate(layout.abc_dialog_title_material, (ViewGroup)null); this.mHasActionBar = this.mOverlayActionBar = false; } else if (this.mHasActionBar) { TypedValue outValue = new TypedValue(); this.mContext.getTheme().resolveAttribute(attr.actionBarTheme, outValue, true); Object themedContext; if (outValue.resourceId != 0) { themedContext = new ContextThemeWrapper(this.mContext, outValue.resourceId); } else { themedContext = this.mContext; } subDecor = (ViewGroup)LayoutInflater.from((Context)themedContext).inflate(layout.abc_screen_toolbar, (ViewGroup)null); this.mDecorContentParent = (DecorContentParent)subDecor.findViewById(id.decor_content_parent); this.mDecorContentParent.setWindowCallback(this.getWindowCallback()); if (this.mOverlayActionBar) { this.mDecorContentParent.initFeature(109); } if (this.mFeatureProgress) { this.mDecorContentParent.initFeature(2); } if (this.mFeatureIndeterminateProgress) { this.mDecorContentParent.initFeature(5); } } } else { if (this.mOverlayActionMode) { subDecor = (ViewGroup)inflater.inflate(layout.abc_screen_simple_overlay_action_mode, (ViewGroup)null); } else { subDecor = (ViewGroup)inflater.inflate(layout.abc_screen_simple, (ViewGroup)null); } if (VERSION.SDK_INT >= 21) { ViewCompat.setOnApplyWindowInsetsListener(subDecor, new OnApplyWindowInsetsListener() { public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) { int top = insets.getSystemWindowInsetTop(); int newTop = AppCompatDelegateImpl.this.updateStatusGuard(top); if (top != newTop) { insets = insets.replaceSystemWindowInsets(insets.getSystemWindowInsetLeft(), newTop, insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom()); } return ViewCompat.onApplyWindowInsets(v, insets); } }); } else { ((FitWindowsViewGroup)subDecor).setOnFitSystemWindowsListener(new OnFitSystemWindowsListener() { public void onFitSystemWindows(Rect insets) { insets.top = AppCompatDelegateImpl.this.updateStatusGuard(insets.top); } }); } } if (subDecor == null) { throw new IllegalArgumentException("AppCompat does not support the current theme features: { windowActionBar: " + this.mHasActionBar + ", windowActionBarOverlay: " + this.mOverlayActionBar + ", android:windowIsFloating: " + this.mIsFloating + ", windowActionModeOverlay: " + this.mOverlayActionMode + ", windowNoTitle: " + this.mWindowNoTitle + " }"); } else { if (this.mDecorContentParent == null) { this.mTitleView = (TextView)subDecor.findViewById(id.title); } ViewUtils.makeOptionalFitsSystemWindows(subDecor); ContentFrameLayout contentView = (ContentFrameLayout)subDecor.findViewById(id.action_bar_activity_content); ViewGroup windowContentView = (ViewGroup)this.mWindow.findViewById(16908290); if (windowContentView != null) { while(windowContentView.getChildCount() > 0) { View child = windowContentView.getChildAt(0); windowContentView.removeViewAt(0); contentView.addView(child); } windowContentView.setId(-1); contentView.setId(16908290); if (windowContentView instanceof FrameLayout) { ((FrameLayout)windowContentView).setForeground((Drawable)null); } } // 將 subDecor 添加到 DecorView 中 this.mWindow.setContentView(subDecor); contentView.setAttachListener(new OnAttachListener() { public void onAttachedFromWindow() { } public void onDetachedFromWindow() { AppCompatDelegateImpl.this.dismissPopups(); } }); return subDecor; } } }
上面的代碼總結來講就是在作一件事,就是建立 subDecor。攤開來講具體以下:
一、根據用戶選擇的主題來設置一些顯示特性,包括標題,actionbar 等。
二、根據不一樣特性來初始化 subDecor;對 subDecor 內部的子 View 進行初始化。
三、最後添加到 DecorView中。
添加的具體代碼以下:此處是經過調用
// AppCompatDelegateImpl this.mWindow.getDecorView();
// phoneWindow public final View getDecorView() {
if (mDecor == null || mForceDecorInstall) {
installDecor();
}
return mDecor;
}
private void installDecor() {
mForceDecorInstall = false;
if (mDecor == null) {
// 生成 DecorView mDecor = generateDecor(-1);
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
}
} else {
// 這樣 DecorView 就持有了window mDecor.setWindow(this);
}
......
}
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());
}
到此,DecorView 的建立就講完了。但是咱們彷佛並無看到 DecorView 是被添加的,何時對用戶可見的。
View 建立完之後,那 Decorview 是怎麼添加到屏幕中去的呢?固然是 WindowManager 呢,那麼是如何將 View 傳到 WindowManager 中呢。
看 ActivityThread 中的 handleResumeActivity 方法:
// ActivityThread
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward, String reason) { ...... 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(); 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); } } // 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) { // 這裏也會調用addview r.activity.makeVisible(); } } r.nextIdle = mNewActivities; mNewActivities = r; if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r); Looper.myQueue().addIdleHandler(new Idler()); }
上面的代碼主要作了如下幾件事:
一、獲取到 DecorView,設置不可見,而後經過 wm.addView(decor, l) 將 view 添加到 WindowManager;
二、在某些狀況下,好比此時點擊了輸入框調起了鍵盤,就會調用 wm.updateViewLayout(decor, l) 來更新 View 的佈局。
三、這些作完之後,會調用 activity 的 makeVisible ,讓視圖可見。若是此時 DecorView 沒有添加到 WindowManager,那麼會添加。
// Activity
void makeVisible() { if (!mWindowAdded) { ViewManager wm = getWindowManager(); wm.addView(mDecor, getWindow().getAttributes()); mWindowAdded = true; } mDecor.setVisibility(View.VISIBLE); }
接下來,看下 addview 的邏輯。 WindowManager 的實現類是 WindowManagerImpl,而它則是經過 WindowManagerGlobal 代理實現 addView 的,咱們看下 addView 的方法:
// WindowManagerGlobal public void addView(View view, ViewGroup.LayoutParams params, Display display, Window parentWindow) { // ...... 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 。同時調用 ViewRootImpl 的 setView 方法來持有了 DecorView。此外這裏還保存了 DecorView ,Params,以及 ViewRootImpl 的實例。
如今咱們終於知道爲啥 View 是在 OnResume 的時候可見的呢。
實際上,View 的繪製是由 ViewRootImpl 來負責的。每一個應用程序窗口的 DecorView 都有一個與之關聯的 ViewRootImpl 對象,這種關聯關係是由 WindowManager 來維護的。
先看 ViewRootImpl 的 setView 方法,該方法很長,咱們將一些不重要的點註釋掉:
/** * We have one child */ public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) { synchronized (this) { if (mView == null) { mView = view; ...... mAdded = true; int res; /* = WindowManagerImpl.ADD_OKAY; */ // 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(); ...... } } }
這裏先將 mView 保存了 DecorView 的實例,而後調用 requestLayout() 方法,以完成應用程序用戶界面的初次佈局。
public void requestLayout() { if (!mHandlingLayoutInLayoutRequest) { checkThread(); mLayoutRequested = true; scheduleTraversals(); } }
由於是 UI 繪製,因此必定要確保是在主線程進行的,checkThread 主要是作一個校驗。接着調用 scheduleTraversals 開始計劃繪製了。
void scheduleTraversals() { if (!mTraversalScheduled) { mTraversalScheduled = true; mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier(); mChoreographer.postCallback( Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null); if (!mUnbufferedInputDispatch) { scheduleConsumeBatchedInput(); } notifyRendererOfFramePending(); pokeDrawLockIfNeeded(); } }
這裏主要關注兩點:
mTraversalBarrier : Handler 的同步屏障。它的做用是能夠攔截 Looper 對同步消息的獲取和分發,加入同步屏障以後,Looper 只會獲取和處理異步消息,若是沒有異步消息那麼就會進入阻塞狀態。也就是說,對 View 繪製渲染的處理操做能夠優先處理(設置爲異步消息)。
mChoreographer: 編舞者。統一動畫、輸入和繪製時機。也是這章須要重點分析的內容。
mTraversalRunnable :TraversalRunnable 的實例,是一個Runnable,最終確定會調用其 run 方法:
final class TraversalRunnable implements Runnable { @Override public void run() { doTraversal(); } }
doTraversal,如其名,開始繪製了,該方法內部最終會調用 performTraversals 進行繪製。
void doTraversal() { if (mTraversalScheduled) { mTraversalScheduled = false; mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier); if (mProfile) { Debug.startMethodTracing("ViewAncestor"); } performTraversals(); if (mProfile) { Debug.stopMethodTracing(); mProfile = false; } } }
到此,DecorView 與 activity 之間的綁定關係就講完了,下一章,將會介紹 performTraversals 所作的事情,也就是 View 繪製流程。