面試官帶你學(xué)安卓 - 從安卓的事件分發(fā)說起

一、題目層次

面試中提到安卓的事件分發(fā),我們一般都能說到從 Activity -> Window -> DecorView -> ViewGroup -> View 的 dispatchTouchEvent 流程,這個是最基本的需要掌握的,由此能深入引出一些什么知識點呢?

  1. 事件是如何從屏幕點擊最終到達 Activity 的?
  2. CANCEL 事件什么時候會觸發(fā)?
  3. 如何解決滑動沖突?

二、題目詳解

2.1 安卓事件的分發(fā)

安卓的事件分發(fā)大概會經(jīng)歷 Activity -> PhoneWindow -> DecorView -> ViewGroup -> View 的 dispatchTouchEvent。
其中 dispatchTouchEvent 用下面的一段偽代碼就可以說明了,過程就不具體分析了,大家應(yīng)該也都比較清晰。

// 偽代碼
public boolean dispatchTouchEvent() {
    boolean res = false;

    // 是否不允許攔截事件
    // 如果設(shè)置了 FLAG_DISALLOW_INTERCEPT,不會攔截事件,所以在 child 里可以通過 requestDisallowInterceptTouchEvent 控制父 View 是否來攔截事件
    final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;

    if (!disallowIntercept && onInterceptTouchEvent()) { // View 不調(diào)用這里,直接執(zhí)行下面的 touchlistener 判斷
        if (touchlistener && touchlistener.onTouch()) {
            return true;
        }
        res = onTouchEvent(); // 里面會處理點擊事件 -> performClick() -> clicklistener.onClick()
    } else if (DOWN) { // 如果是 DOWN 事件,則遍歷子 View 進行事件分發(fā)
        // 循環(huán)子 View 處理事件
        for (childs) {
            res = child.dispatchTouchEvent();
        }
    } else {
        // 事件分發(fā)給 target 去處理,這里的 target 就是上一步處理 DOWN 事件的 View
        target.child.dispatchTouchEvent();
    }
    return res;
}
復(fù)制代碼

2.2 事件是如何到達 Activity 的

既然上面的事件分發(fā)是從 Activity 開始的,那事件是怎么到達 Activity 的呢?

總體流程大概是這樣的:用戶點擊設(shè)備, linux 內(nèi)核接受中斷, 中斷加工成輸入事件數(shù)據(jù)寫入對應(yīng)的設(shè)備節(jié)點中, InputReader 會監(jiān)控 /dev/input/ 下的所有設(shè)備節(jié)點, 當(dāng)某個節(jié)點有數(shù)據(jù)可以讀時,通過 EventHub 將原始事件取出來并翻譯加工成輸入事件,交給 InputDispatcher,InputDispatcher 根據(jù) WMS 提供的窗口信息把事件交給合適的窗口,窗口 ViewRootImpl 派發(fā)事件

大體流程圖如下:

其中主要有幾個階段:

  1. 硬件中斷
  2. InputManagerService 做的事情
  3. InputReaderThread 做的事情
  4. InputDispatcherThread 做的事情
  5. WindowInputEventReceiver 做的事情
2.2.1 硬件中斷

硬件中斷這里就簡單介紹一些,操作系統(tǒng)對硬件事件的接收是通過中斷來進行的。
內(nèi)核啟動的時候會在中斷描述符表中對中斷類型以及對應(yīng)的處理方法的地址進行注冊。
當(dāng)有中斷的時候,就會調(diào)用對應(yīng)的處理方法,把對應(yīng)的事件寫入到設(shè)備節(jié)點里。

2.2.2 InputManagerService 做的事情

InputManagerService 是用來處理 Input 事件的,Java 側(cè)的 InputManagerService 就是 C++ 代碼的一個封裝,以及提供了一些 callback 用來傳遞事件到 Java 層。
我們看一下 native 側(cè)的 InputManagerService 初始化代碼。

NativeInputManager::NativeInputManager(jobject contextObj,
        jobject serviceObj, const sp<Looper>& looper) :
        mLooper(looper), mInteractive(true) {
    // ...
    sp<EventHub> eventHub = new EventHub();
    mInputManager = new InputManager(eventHub, this, this);
}
復(fù)制代碼

主要做的兩件事:

  1. 初始化 EventHub
EventHub::EventHub(void) {
            // ...
    mINotifyFd = inotify_init();
    int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
    result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
    result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
}
復(fù)制代碼

EventHub 的作用是用來監(jiān)控設(shè)備節(jié)點是否有更新。
2. 初始化 InputManager

void InputManager::initialize() {
    mReaderThread = new InputReaderThread(mReader);
    mDispatcherThread = new InputDispatcherThread(mDispatcher);
}
復(fù)制代碼

InputManager 里初始化了 InputReaderThread 和 InputDispatcherThread 兩個線程,一個用來讀取事件,一個用來派發(fā)事件。

2.2.3 InputReaderThread 做的事情
bool InputReaderThread::threadLoop() {
    mReader->loopOnce();
    return true;
}

void InputReader::loopOnce() {
    // 從 EventHub 獲取事件
    size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
    // 處理事件
    processEventsLocked(mEventBuffer, count);
    // 事件發(fā)送給 InputDispatcher 去做分發(fā)
    mQueuedListener->flush();
}
復(fù)制代碼

這里代碼比較多,做一些省略。
InputReaderThread 里做了三件事情:

  1. 從 EventHub 獲取事件
  2. 處理事件,這里事件有不同的類型,會做不同的處理和封裝
  3. 把事件發(fā)送給 InputDispatcher
2.2.4 InputDispatcherThread 做的事情
bool InputDispatcherThread::threadLoop() {
    mDispatcher->dispatchOnce(); // 內(nèi)部調(diào)用 dispatchOnceInnerLocked
    return true;
}

void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
    // 從隊列中取出一個事件
    mPendingEvent = mInboundQueue.dequeueAtHead();
    // 根據(jù)不同的事件類型,進行不同的操作
    switch (mPendingEvent->type) {
    case EventEntry::TYPE_CONFIGURATION_CHANGED: {
        // ...
    case EventEntry::TYPE_DEVICE_RESET: {
        // ...
    case EventEntry::TYPE_KEY: {
        // ...
    case EventEntry::TYPE_MOTION: {
        // 派發(fā)事件
        done = dispatchMotionLocked(currentTime, typedEntry,
                &dropReason, nextWakeupTime);
        break;
    }
}
復(fù)制代碼

上面通過 dispatchMotionLocked 方法派發(fā)事件,具體的函數(shù)調(diào)用過程省略如下:

dispatchMotionLocked -> dispatchEventLocked -> prepareDispatchCycleLocked -> enqueueDispatchEntriesLocked -> startDispatchCycleLocked -> publishMotionEvent -> InputChannel.sendMessage
復(fù)制代碼

其中會找到當(dāng)前合適的 Window,然后調(diào)用 InputChannel 去發(fā)送事件。

這里的 InputChannel 對應(yīng)的是 ViewRootImpl 里的 InputChannel。
至于中間的怎么做的關(guān)聯(lián),這里就先不做分析,整個代碼比較長,而且對于流程的掌握影響不大。

2.2.5 WindowInputEventReceiver 接受事件并進行分發(fā)

在 ViewRootImpl 里有一個 WindowInputEventReceiver 用來接受事件并進行分發(fā)。
InputChannel 發(fā)送的事件最終都是通過 WindowInputEventReceiver 進行接受。
WindowInputEventReceiver 是在 ViewRootImpl.setView 里面初始化的,setView 的調(diào)用是在 ActivityThread.handleResumeActivity -> WindowManagerGlobal.addView。

    public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
        // ...
        if (mInputChannel != null) {
            if (mInputQueueCallback != null) {
                mInputQueue = new InputQueue();
                mInputQueueCallback.onInputQueueCreated(mInputQueue);
            }
            mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
                    Looper.myLooper());
        }
    }
復(fù)制代碼
public abstract class InputEventReceiver {
    // native 側(cè)代碼調(diào)用這個方法,把事件派發(fā)過來
    private void dispatchInputEvent(int seq, InputEvent event, int displayId) {
        mSeqMap.put(event.getSequenceNumber(), seq);
        onInputEvent(event, displayId);
    }
}

final class WindowInputEventReceiver extends InputEventReceiver {
    @Override
    public void onInputEvent(InputEvent event, int displayId) {
        // 事件接受
        enqueueInputEvent(event, this, 0, true);
    }
    // ...
}

void enqueueInputEvent(InputEvent event,
        InputEventReceiver receiver, int flags, boolean processImmediately) {
    // 是否要立即處理事件
    if (processImmediately) {
        doProcessInputEvents();
    } else {
        scheduleProcessInputEvents();
    }
}

void doProcessInputEvents() {
    // ...
    while (mPendingInputEventHead != null) {
        deliverInputEvent(q);
    }
    // ...
}

private void deliverInputEvent(QueuedInputEvent q) {
    // ...
    InputStage stage;
    if (q.shouldSendToSynthesizer()) {
        stage = mSyntheticInputStage;
    } else {
        stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
    }

    // 分發(fā)事件
    stage.deliver(q);
}
復(fù)制代碼

從上面的代碼流程中,事件最終走到 InputStage.deliver 里。

abstract class InputStage {
    public final void deliver(QueuedInputEvent q) {
        if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) {
            forward(q);
        } else if (shouldDropInputEvent(q)) {
            finish(q, false);
        } else {
            apply(q, onProcess(q));
        }
    }
}
復(fù)制代碼

在 deliver 里,最終調(diào)用 onProcess,實現(xiàn)是在 ViewPostImeInputStage。

final class ViewPostImeInputStage extends InputStage {
    @Override
    protected int onProcess(QueuedInputEvent q) {
        if (q.mEvent instanceof KeyEvent) {
            return processKeyEvent(q);
        } else {
            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);
            }
        }
    }

    private int processPointerEvent(QueuedInputEvent q) {
        // 這里 mView 是 DecorView,調(diào)用到 DecorView.dispatchPointerEvent
        boolean handled = mView.dispatchPointerEvent(event);
        // ...
        return handled ? FINISH_HANDLED : FORWARD;
    }
}

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

// DecorView.java
public boolean dispatchTouchEvent(MotionEvent ev) {
    // 這里的 Callback 就是 Activity,是在 Activity.attach 里調(diào)用 mWindow.setCallback(this); 設(shè)置的
    final Window.Callback cb = mWindow.getCallback();
    return cb != null && !mWindow.isDestroyed() && mFeatureId < 0
            ? cb.dispatchTouchEvent(ev) : super.dispatchTouchEvent(ev);
}
復(fù)制代碼

通過上面一系列流程,最終就調(diào)用到 Activity.dispatchTouchEvent 里,也就是開始的流程了。

通過上面的分析,我們基本上知道了事件從用戶點擊屏幕到 View 處理的過程了,就是下面這張圖。

2.3 CANCEL 事件什么時候會觸發(fā)

這個如果仔細看 dispatchTouchEvent 的代碼的話,可以看到一些時機:

  1. View 收到 ACTION_DOWN 事件以后,上一個事件還沒有結(jié)束(可能因為 APP 的切換、ANR 等導(dǎo)致系統(tǒng)扔掉了后續(xù)的事件),這個時候會先執(zhí)行一次 ACTION_CANCEL
// ViewGroup.dispatchTouchEvent()
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (actionMasked == MotionEvent.ACTION_DOWN) {
        // Throw away all previous state when starting a new touch gesture.
        // The framework may have dropped the up or cancel event for the previous gesture
        // due to an app switch, ANR, or some other state change.
        cancelAndClearTouchTargets(ev);
        resetTouchState();
    }
}
復(fù)制代碼
  1. 子 View 之前攔截了事件,但是后面父 View 重新攔截了事件,這個時候會給子 View 發(fā)送 ACTION_CANCEL 事件
// ViewGroup.dispatchTouchEvent()
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (mFirstTouchTarget == null) {
    } else {
        // 有子 View 獲取了事件
        TouchTarget target = mFirstTouchTarget;
        while (target != null) {
            final TouchTarget next = target.next;
            final boolean cancelChild = resetCancelNextUpFlag(target.child)
                    || intercepted;
            // 父 View 此時如果攔截了事件,cancelChild 是 true
            if (dispatchTransformedTouchEvent(ev, cancelChild,
                    target.child, target.pointerIdBits)) {
                handled = true;
            }
        }
    }
}

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
        View child, int desiredPointerIdBits) {
    final int oldAction = event.getAction();
    // 如果 cancel 是 true,則發(fā)送 ACTION_CANCEL 事件
    if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
        event.setAction(MotionEvent.ACTION_CANCEL);
        if (child == null) {
            handled = super.dispatchTouchEvent(event);
        } else {
            handled = child.dispatchTouchEvent(event);
        }
        event.setAction(oldAction);
        return handled;
    }
}
復(fù)制代碼

2.4 如何解決滑動沖突

這個也是老生常談的一個問題了,主要就是兩個方法:

  1. 通過重寫父類的 onInterceptTouchEvent 來攔截滑動事件
  2. 通過在子類中調(diào)用 parent.requestDisallowInterceptTouchEvent 來通知父類是否要攔截事件,requestDisallowInterceptTouchEvent 會設(shè)置 FLAG_DISALLOW_INTERCEPT 標志,這個在最開始的偽代碼那里做過介紹

三、總結(jié)

上面就是從 View 事件分發(fā)引申出的一些問題,簡單的解答如下:

  1. View 事件分發(fā)
// 偽代碼
public boolean dispatchTouchEvent() {
    boolean res = false;

    // 是否不允許攔截事件
    // 如果設(shè)置了 FLAG_DISALLOW_INTERCEPT,不會攔截事件,所以在 child 里可以通過 requestDisallowInterceptTouchEvent 控制父 View 是否來攔截事件
    final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;

    if (!disallowIntercept && onInterceptTouchEvent()) { // View 不調(diào)用這里,直接執(zhí)行下面的 touchlistener 判斷
        if (touchlistener && touchlistener.onTouch()) {
            return true;
        }
        res = onTouchEvent(); // 里面會處理點擊事件 -> performClick() -> clicklistener.onClick()
    } else if (DOWN) { // 如果是 DOWN 事件,則遍歷子 View 進行事件分發(fā)
        // 循環(huán)子 View 處理事件
        for (childs) {
            res = child.dispatchTouchEvent();
        }
    } else {
        // 事件分發(fā)給 target 去處理,這里的 target 就是上一步處理 DOWN 事件的 View
        target.child.dispatchTouchEvent();
    }
    return res;
}
復(fù)制代碼
  1. 事件是如何從屏幕點擊最終到達 Activity 的?


  2. CANCEL 事件什么時候會觸發(fā)?

  • View 收到 ACTION_DOWN 事件以后,上一個事件還沒有結(jié)束(可能因為 APP 的切換、ANR 等導(dǎo)致系統(tǒng)扔掉了后續(xù)的事件),這個時候會先執(zhí)行一次 ACTION_CANCEL
  • 子 View 之前攔截了事件,但是后面父 View 重新攔截了事件,這個時候會給子 View 發(fā)送 ACTION_CANCEL 事件
  1. 如何解決滑動沖突?
  • 通過重寫父類的 onInterceptTouchEvent 來攔截滑動事件
  • 通過在子類中調(diào)用 parent.requestDisallowInterceptTouchEvent 來通知父類是否要攔截事件

作者:ZYLAB
鏈接:https://juejin.im/post/6874589638925746190

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容