Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android ViewRootImpl 源碼深度解析:Window、View 與事件分發的核心

編輯:關於 Android 程式設計

ViewRoot 這個類如今已經不復存在,它是老版本中的類別。從 Android 2.2 開始,系統用 ViewRootImpl 取代了 ViewRoot,對應 ViewRootImpl.java。它是連接 WindowManager 與 DecorView 的紐帶,同時 View 的繪制也是通過 ViewRootImpl 完成的。

總結起來,它主要有三大作用:

A:作為鏈接 WindowManager 和 DecorView 的紐帶,更廣義地說是 Window 與 View 之間的紐帶。

B:完成 View 的繪制過程,包括 measure、layout、draw。

C:向 DecorView 分發用戶觸發的 event 事件,如按鍵、觸屏等。

(如有分析不當之處,歡迎批評指正。)

一、鏈接 WindowManager 和 DecorView

先看 ViewRootImpl.java 開頭的類註釋:

/**
 * The top of a view hierarchy, implementing the needed protocol between View
 * and the WindowManager. This is for the most part an internal implementation
 * detail of {@link WindowManagerGlobal}.
 *
 * {@hide}
 */

由此不難看出,ViewRootImpl 是 View 樹的樹根,但它本身並不是 View,而是實現了 View 與 WindowManager 之間的通信協議,具體實現則在 WindowManagerGlobal 中。

那麼 View 與 WindowManager 是怎麼建立聯系的呢?WindowManager 提供的功能很簡單,常用方法只有三個:添加 View、更新 View 和刪除 View(此外還有改變 Window 位置等)。這三個方法定義在 ViewManager 接口中,而 WindowManager 繼承了 ViewManager。

public interface ViewManager {
    public void addView(View view, ViewGroup.LayoutParams params);
    public void updateViewLayout(View view, ViewGroup.LayoutParams params);
    public void removeView(View view);
}

Window 是一個抽象的概念,每個 Window 都對應一個 View 和一個 ViewRootImpl,Window 通過 ViewRootImpl 與 View 建立聯系,因此 Window 並非實際存在,而是以 View 的形式存在。這一點從 WindowManager 的定義也能看出:它提供的 addView、updateView、removeView 都是針對 View 的,說明 View 才是 Window 的實體。實際使用中我們無法直接訪問 Window,必須通過 WindowManager,而對 Window 的添加、更新、刪除最終都由 ViewRootImpl 實現。下面以 Window 的添加過程為例。

Window 的添加過程

Window 的添加需通過 WindowManager 的 addView 實現。WindowManager 是接口,其實現類是 WindowManagerImpl,其中的三大操作如下:

@Override
public void addView(View view, ViewGroup.LayoutParams params) {
    mGlobal.addView(view, params, mDisplay, mParentWindow);
}
@Override
public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
    mGlobal.updateViewLayout(view, params);
}
@Override
public void removeView(View view) {
    mGlobal.removeView(view, false);
}
@Override
public void removeViewImmediate(View view) {
    mGlobal.removeView(view, true);
}

可以看出,WindowManagerImpl 又轉調了 WindowManagerGlobal 的三大操作方法,這正好印證了 ViewRootImpl 類開頭那句註釋。

addView 方法大致分為三步:

1、檢查參數是否合法

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

2、創建 ViewRootImpl 並將 View 添加到列表中

WindowManagerGlobal 內部有幾個重要列表:

private final ArrayList mViews = new ArrayList();
private final ArrayList mRoots = new ArrayList();
private final ArrayList mParams = new ArrayList();
private final ArraySet mDyingViews = new ArraySet();

其中,mViews 存儲所有 Window 對應的 View,mRoots 存儲所有對應的 ViewRootImpl,mParams 存儲布局參數,mDyingViews 存儲那些已調用 removeView 但尚未刪除的 View。addView 中通過如下方式添加到列表:

root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);

3、通過 ViewRootImpl 更新界面並完成 Window 添加

這一步由 ViewRootImpl 的 setView 方法完成:

root.setView(view, wparams, panelParentView);

setView 內部會通過 requestLayout 完成異步刷新請求,最終調用 performTraversals 完成 View 繪制。源碼註釋大意为:在加入 WindowManager 之前先完成第一次 layout,以確保在收到任何系統事件前完成重新布局。

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

接著通過 WindowSession 完成 Window 添加。下面代碼中 mWindowSession 類型為 IWindowSession,是一個 Binder 對象,真正實現類是 Session,也就是說這其實是一次 IPC 過程,遠程調用了 Session 的 addToDisplay 方法。

try {
    mOrigWindowType = mWindowAttributes.type;
    mAttachInfo.mRecomputeGlobalAttributes = true;
    collectViewAttributes();
    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
            getHostVisibility(), mDisplay.getDisplayId(),
            mAttachInfo.mContentInsets, mInputChannel);
} catch (RemoteException e) {
    mAdded = false;
    mView = null;
    mAttachInfo.mRootView = null;
    mInputChannel = null;
    mFallbackEventHandler.setView(null);
    unscheduleTraversals();
    setAccessibilityFocus(null, null);
    throw new RuntimeException("Adding window failed", e);
}

Session 的 addToDisplay 方法(位於 package com.android.server.wm):

@Override
public int addToDisplay(IWindow window, int seq, WindowManager.LayoutParams attrs,
        int viewVisibility, int displayId, Rect outContentInsets, InputChannel outInputChannel) {
    return mService.addWindow(this, window, seq, attrs, viewVisibility,
            displayId, outContentInsets, outInputChannel);
}

可見 Window 的添加請求最終交給了 WindowManagerService 處理。addView 的整體鏈路為:

WindowManager ——> WindowManagerGlobal ——> ViewRootImpl ——> Session ——> WindowManagerService

那麼 WindowManager 又是如何與 DecorView 相連的呢?最終 DecorView 一定要添加到 Window 上,而 Window 的具體實現類是 PhoneWindow,DecorView 就嵌入其中:

在 ActivityThread 中,Activity 對象創建完畢後,會將 DecorView 添加到 Window,同時創建 ViewRootImpl 並與 DecorView 建立關聯:

r.window = r.activity.getWindow();
View decor = r.window.getDecorView(); // 獲得 DecorView
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) {
    a.mWindowAdded = true;
    wm.addView(decor, l); // 通過 WindowManager 添加 decorView
}

我們平時在 Activity 調用 setContentView 時,會轉調 PhoneWindow 的 setContentView,最終調用 DecorView 的 addView,這也說明了我們添加的 View 是 DecorView 的子元素。

二、完成 View 的繪制過程

整個 View 樹的繪圖流程始於 ViewRootImpl 的 performTraversals() 方法(這個方法很長)。它主要根據之前設置的狀態,判斷是否需要重新計算大小(measure)、重新放置位置(layout)以及重繪(draw),核心就是按順序選擇執行這三個方法:

private void performTraversals() {
    // 最外層根視圖的 widthMeasureSpec 和 heightMeasureSpec 由來
    // lp.width 和 lp.height 在創建 ViewGroup 實例時等於 MATCH_PARENT
    int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
    int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
    mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    mView.layout(0, 0, mView.getMeasuredWidth(), mView.getMeasuredHeight());
    mView.draw(canvas);
}

performTraversals 經過 measure、layout、draw 三個過程才能把 View 繪制出來,所以 View 的繪制由 ViewRootImpl 完成。此外,手動調用 invalidate、postInvalidate、requestInvalidate 最終也會調用 performTraversals 重新繪制 View。其中 requestLayout() 只會調用 measure 和 layout,不會調用 draw,也不會重繪任何 View(包括調用者本身)。

三、向 DecorView 分發事件

這裡的事件不僅包括 MotionEvent,還有 KeyEvent。我們知道 View 的事件分發順序為 Activity ——> Window ——> View,那 Activity 的事件來源在哪裡?答案與 ViewRootImpl 關係密切。

事件的根本來源是 Native 層的嵌入式硬件,然後經 InputEventReceiver 接收,交給 ViewRootImpl,再傳給 DecorView,DecorView 交給 PhoneWindow,PhoneWindow 再交給 Activity。整個事件分發順序如下:

先看 ViewRootImpl 的 dispatchInputEvent 方法:

public void dispatchInputEvent(InputEvent event, InputEventReceiver receiver) {
    SomeArgs args = SomeArgs.obtain();
    args.arg1 = event;
    args.arg2 = receiver;
    Message msg = mHandler.obtainMessage(MSG_DISPATCH_INPUT_EVENT, args);
    msg.setAsynchronous(true);
    mHandler.sendMessage(msg);
}

InputEvent 有兩個子類:KeyEvent(鍵盤事件)和 MotionEvent(點擊事件)。InputEventReceiver 即「輸入事件接收者」,負責接收輸入事件並交給 dispatchInputEvent 分發。可以看到 mHandler 把邏輯切換到了 UI 線程:

final ViewRootHandler mHandler = new ViewRootHandler();
final class ViewRootHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_DISPATCH_INPUT_EVENT: {
                SomeArgs args = (SomeArgs) msg.obj;
                InputEvent event = (InputEvent) args.arg1;
                InputEventReceiver receiver = (InputEventReceiver) args.arg2;
                enqueueInputEvent(event, receiver, 0, true);
                args.recycle();
            } break;
        }
    }
}

在 mHandler 的 UI 線程中最終調用了 enqueueInputEvent 方法,它將輸入事件打包成 QueuedInputEvent,加入待處理隊列:

void enqueueInputEvent(InputEvent event, InputEventReceiver receiver,
        int flags, boolean processImmediately) {
    QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
    QueuedInputEvent last = mPendingInputEventTail;
    if (last == null) {
        mPendingInputEventHead = q;
        mPendingInputEventTail = q;
    } else {
        last.mNext = q;
        mPendingInputEventTail = q;
    }
    mPendingInputEventCount += 1;
    if (processImmediately) {
        doProcessInputEvents();
    } else {
        scheduleProcessInputEvents();
    }
}

enqueueInputEvent 會根據標志位 processImmediately 決定同步或異步調用 doProcessInputEvents 或 scheduleProcessInputEvents。後者只是向 UI 線程發送一個 message:

private void scheduleProcessInputEvents() {
    if (!mProcessInputEventsScheduled) {
        mProcessInputEventsScheduled = true;
        Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
        msg.setAsynchronous(true);
        mHandler.sendMessage(msg);
    }
}

可見即使調用 scheduleProcessInputEvents,最終還是會調用 doProcessInputEvents,只是同步與異步的區別。doProcessInputEvents 會逐個分發隊列中的事件:

void doProcessInputEvents() {
    while (mPendingInputEventHead != null) {
        QueuedInputEvent q = mPendingInputEventHead;
        mPendingInputEventHead = q.mNext;
        if (mPendingInputEventHead == null) {
            mPendingInputEventTail = null;
        }
        q.mNext = null;
        mPendingInputEventCount -= 1;
        deliverInputEvent(q);
    }
    if (mProcessInputEventsScheduled) {
        mProcessInputEventsScheduled = false;
        mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
    }
}

它其實就是單鏈表的遍歷操作,逐個取出並分發,處理完後清除標志位。分發過程通過 deliverInputEvent 方法:

private void deliverInputEvent(QueuedInputEvent q) {
    if (mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);
    }
    InputStage stage;
    if (q.shouldSendToSynthesizer()) {
        stage = mSyntheticInputStage;
    } else {
        stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
    }
    if (stage != null) {
        stage.deliver(q);
    } else {
        finishInputEvent(q);
    }
}

ViewRootImpl 中有一系列類似 InputStage(輸入事件舞台)的概念,它是一個抽象類,deliver 方法會處理一個輸入事件,處理完後調用 finishInputEvent。它有許多子類,如 AsyncInputStage、SyntheticInputStage、NativePostImeInputStage、ViewPreImeInputStage、ViewPostImeInputStage 等,分別處理不同的事件類型。

當一個 InputEvent 到來時,ViewRootImpl 會尋找合適的 InputStage 處理。對於點擊事件,ViewPostImeInputStage 可以處理,其 onProcess 方法如下:

@Override
protected int onProcess(QueuedInputEvent q) {
    if (q.mEvent instanceof KeyEvent) {
        return processKeyEvent(q);
    } else {
        handleDispatchDoneAnimating();
        final int source = q.mEvent.getSource();
        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
            return processPointerEvent(q);
        } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
            return processTrackballEvent(q);
        } else {
            return processGenericMotionEvent(q);
        }
    }
}

在 processKeyEvent、processPointerEvent、processTrackballEvent、processGenericMotionEvent 方法中都有幾句關鍵代碼:

mView.dispatchKeyEvent(event)          // 按鍵事件
mView.dispatchPointerEvent(event)      // 指針事件
mView.dispatchTrackballEvent(event)    // 軌跡球事件
mView.dispatchGenericMotionEvent(event) // 通用運動事件

可以看到 mView 並未在這裡實例化,它的實例化在 setView 方法中完成:

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
    synchronized (this) {
        if (mView == null) {
            mView = view;
            ...
        }
    }
}

而傳入 setView 的 view 參數正是 DecorView,所以這裡的 mView 其實就是 DecorView。基於多態,如果 DecorView 實現了上述方法就調用 DecorView 的,否則調用 View 的。跟蹤 View 的 dispatchPointerEvent:

public final boolean dispatchPointerEvent(MotionEvent event) {
    if (event.isTouchEvent()) {
        return dispatchTouchEvent(event);
    } else {
        return dispatchGenericMotionEvent(event);
    }
}

它會調用 dispatchTouchEvent,最終基於多態傳給 DecorView 的 dispatchTouchEvent:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    final Callback cb = getCallback();
    return cb != null && !isDestroyed() && mFeatureId < 0
            ? cb.dispatchTouchEvent(ev) : super.dispatchTouchEvent(ev);
}

DecorView 最終調用 cb.dispatchTouchEvent,那麼這個 Callback 是什麼呢?其實它就是當前的 Activity。因為 Activity 實現了 Window.Callback 接口:

public class Activity extends ContextThemeWrapper implements LayoutInflater.Factory2,
        Window.Callback, KeyEvent.Callback, OnCreateContextMenuListener,
        ComponentCallbacks2, Window.OnWindowDismissedCallback {

在 Activity 的 attach 方法中,PhoneWindow 通過 setCallback 將 Callback 設置為 this,也就是 Activity:

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) {
    attachBaseContext(context);
    mFragments.attachHost(null);
    mWindow = new PhoneWindow(this);
    mWindow.setCallback(this);
    mWindow.setOnWindowDismissedCallback(this);
    mWindow.getLayoutInflater().setPrivateFactory(this);
    ...
}

至此,點擊事件已經到達 Activity,後續便進入了大家熟悉的事件分發機制。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved