Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 關於Android事件派發流程的理解

關於Android事件派發流程的理解

編輯:關於Android編程

以前看了很多人介紹的Android事件派發流程,但最近使用那些來寫代碼的時候出現了不少錯誤。所以回顧一下整個流程,簡單介紹從手觸摸屏幕開始到事件在View樹派發。從源碼上分析ViewGroup.dispatchTouchEvent。

事件從觸摸到View簡述

Android的事件產生是從我們觸摸屏幕開始,在經過Input子系統,最後達到我們的應用程序(或者經過WindowManagerService到達應用程序)。

而其中Input子系統在Java層對應著InputManagerService,其主要在native層,由InputReader讀取EventHub的元數據,將這些數據加工成InputEvent,最後發到InputDispatcher,而InputDispatcher則負責將時間發到應用程序,Input子系統流程可以參見這篇文章Android Framework——之Input子系統。

對於應用層的時間流程,主要是下面的流程圖所示:
這裡寫圖片描述
其中最後一步就是我們經常說的View事件派發流程。另外上面DecorView是經過了兩次,第一次是調用DecorView的dispatchTouchEvent,它的源碼是:

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

Callback就是Window.Callback,Activity實現了這個接口。在Activity的attach函數中,會調用window的setCallback,將Activity設置給Window。所以這裡getCallback返回的就是Activity,最終會調用Activity的dispatchTouchEvent。下面看一下Activity的dispatchTouchEvent函數:

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

在ACTION_DOWN的時候會調用onUserInteraction方法,然後調用Window(實際上是PhoneWindow)的superDispatchTouchEvent,如果Window的superDispatchTouchEvent消耗了事件,則直接返回,不會調用Activity的onTouchEvent方法。

@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
    return mDecor.superDispatchTouchEvent(event);
}

而DecorView的superDispatchTouchEvent為:

public boolean superDispatchTouchEvent(MotionEvent event) {
    return super.dispatchTouchEvent(event);
}

最終還是調用DecorView的父類的dispatchTouchEvent,DecorView的父類是FrameLayout,它沒實現該方法,最終會調用ViewGroup的dispatchTouchEvent方法。從這裡開始就進入了view樹的時間派發流程了。

View樹的事件派發流程

這裡從源碼上分析事件派發的一些特性。事件派發最開始會進入到ViewGroup的dispatchTouchEvent(DecorVIew父類),下面是ViewGroup的dispatchTouchEvent偽代碼的分析,直接在對應的代碼部分加了注釋:

“`
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//一開始做一些調試驗證,另外如果事件的目標是focused view,並且當前view就是一個focused view,
//有可能view的子View就會處理這次事件,所以將targetAccessibilityFocus設置為false。

    boolean handled = false;
    if (onFilterTouchEventForSecurity(ev)) { //檢查event是否是安全的
        final int action = ev.getAction();
        final int actionMasked = action & MotionEvent.ACTION_MASK;

        // Handle an initial down.
        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.
            //清除之前的事件狀態。比如說在app切換,ANR或其他狀態改變時,系統框架將會去掉up或cancel事件。在這裡會將mFirstTouchTarget清空,mFirstTouchTarget是保存了會接受事件的View處理對象。
            cancelAndClearTouchTargets(ev);
            resetTouchState(); //這裡會將mGroupFlags的FLAG_DISALLOW_INTERCEPT標識清除,
            //1. 每次事件流開始的時候都會先清除FLAG_DISALLOW_INTERCEPT,所以子view的requestDisallowInterceptTouchEvent只有當次事件流有效。
        }

        // 判斷是否需要攔截事件,去判斷是否攔截事件的條件是此次事件是DOWN事件,或者有子類會處理這次事件(mFirstTouchTarget不為null),並且FLAG_DISALLOW_INTERCEPT沒被設置。
        final boolean intercepted;
        if (actionMasked == MotionEvent.ACTION_DOWN
                || mFirstTouchTarget != null) {
            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
            if (!disallowIntercept) {
                //2. 只有有TouchTarget並且沒有被disallow,或者是ACTION_DOWN時才會調用onInterceptTouchEvent。
                intercepted = onInterceptTouchEvent(ev);
                ev.setAction(action); // restore action in case it was changed
            } else {
                intercepted = false;
            }
        } else {
            // There are no touch targets and this action is not an initial down
            // so this view group continues to intercept touches.
            intercepted = true;
        }

        // If intercepted, start normal event dispatch. Also if there is already
        // a view that is handling the gesture, do normal event dispatch.
        if (intercepted || mFirstTouchTarget != null) {
            ev.setTargetAccessibilityFocus(false);
        }

        // Check for cancelation.判斷是否取消
        final boolean canceled = resetCancelNextUpFlag(this)
                || actionMasked == MotionEvent.ACTION_CANCEL;

        // Update list of touch targets for pointer down, if needed.
        final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
        TouchTarget newTouchTarget = null;
        boolean alreadyDispatchedToNewTouchTarget = false;
        if (!canceled && !intercepted) {

            // If the event is targeting accessiiblity focus we give it to the
            // view that has accessibility focus and if it does not handle it
            // we clear the flag and dispatch the event to all children as usual.
            // We are looking up the accessibility focused host to avoid keeping
            // state since these events are very rare.
            View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
                    ? findChildWithAccessibilityFocus() : null;

            if (actionMasked == MotionEvent.ACTION_DOWN
                    || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                    || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                final int actionIndex = ev.getActionIndex(); // always 0 for down
                final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
                        : TouchTarget.ALL_POINTER_IDS;

                // Clean up earlier touch targets for this pointer id in case they
                // have become out of sync.
                removePointersFromTouchTargets(idBitsToAssign);

                final int childrenCount = mChildrenCount;
                if (newTouchTarget == null && childrenCount != 0) {
                    final float x = ev.getX(actionIndex);
                    final float y = ev.getY(actionIndex);
                    // Find a child that can receive the event.
                    // Scan children from front to back.
                    final ArrayList preorderedList = buildOrderedChildList();
                    final boolean customOrder = preorderedList == null
                            && isChildrenDrawingOrderEnabled();
                    final View[] children = mChildren;
                    for (int i = childrenCount - 1; i >= 0; i--) {
                        final int childIndex = customOrder
                                ? getChildDrawingOrder(childrenCount, i) : i;
                        final View child = (preorderedList == null)
                                ? children[childIndex] : preorderedList.get(childIndex);

                        // If there is a view that has accessibility focus we want it
                        // to get the event first and if not handled we will perform a
                        // normal dispatch. We may do a double iteration but this is
                        // safer given the timeframe.
                        if (childWithAccessibilityFocus != null) {
                            if (childWithAccessibilityFocus != child) {
                                continue;
                            }
                            childWithAccessibilityFocus = null;
                            i = childrenCount - 1;
                        }
                        //判斷當前的child是否可以接收事件,並且事件是否在當前的view范圍
                        if (!canViewReceivePointerEvents(child)
                                || !isTransformedTouchPointInView(x, y, child, null)) {
                            ev.setTargetAccessibilityFocus(false);
                            continue;
                        }

                        newTouchTarget = getTouchTarget(child);
                        if (newTouchTarget != null) {
                            // Child is already receiving touch within its bounds.
                            // Give it the new pointer in addition to the ones it is handling.
                            newTouchTarget.pointerIdBits |= idBitsToAssign;
                            break;
                        }

                        resetCancelNextUpFlag(child);
                                    //3.dispatchTransformedTouchEvent會將Event轉化為child坐標空間(getX的變化),然後去除無關的points id,如果有必要更改事件,最後調用child.dispatchTouchEvent。 dispatchTransformedTouchEvent把事件派發給child,如果child成功處理了,則會將child添加到mFirstTouchTarget
                        if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                            // Child wants to receive touch within its bounds.
                            mLastTouchDownTime = ev.getDownTime();
                            if (preorderedList != null) {
                                // childIndex points into presorted list, find original index
                                for (int j = 0; j < childrenCount; j++) {
                                    if (children[childIndex] == mChildren[j]) {
                                        mLastTouchDownIndex = j;
                                        break;
                                    }
                                }
                            } else {
                                mLastTouchDownIndex = childIndex;
                            }
                            mLastTouchDownX = ev.getX();
                            mLastTouchDownY = ev.getY();
                            //addTouchTarget會創建新的TouchTarget,並將其加入到mFirstTouchTarget
                            newTouchTarget = addTouchTarget(child, idBitsToAssign);
                            alreadyDispatchedToNewTouchTarget = true;
                            break;
                        }

                        // The accessibility focus didn't handle the event, so clear
                        // the flag and do a normal dispatch to all children.
                        ev.setTargetAccessibilityFocus(false);
                    }
                    if (preorderedList != null) preorderedList.clear();
                }

                if (newTouchTarget == null && mFirstTouchTarget != null) {
                    // Did not find a child to receive the event.
                    // Assign the pointer to the least recently added target.
                    newTouchTarget = mFirstTouchTarget;
                    while (newTouchTarget.next != null) {
                        newTouchTarget = newTouchTarget.next;
                    }
                    newTouchTarget.pointerIdBits |= idBitsToAssign;
                }
            }
        }

        //4. 派發事件
        // Dispatch to touch targets.
        if (mFirstTouchTarget == null) { //mFirstTouchTarget為空表示沒有子View會處理這次事件,則交給當前的ViewGroup處理。
            // No touch targets so treat this as an ordinary view.
            handled = dispatchTransformedTouchEvent(ev, canceled, null,
                    TouchTarget.ALL_POINTER_IDS);
        } else {
            // Dispatch to touch targets, excluding the new touch target if we already
            // dispatched to it.  Cancel touch targets if necessary.
            TouchTarget predecessor = null;
            TouchTarget target = mFirstTouchTarget; 
            while (target != null) {//遍歷mFirstTouchTarget鏈表,一個一個地處理TouchTarget。
                final TouchTarget next = target.next;
                if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {//新添加的不會立刻處理,ACTION_DOWN已經在前面派發了
                    handled = true;
                } else {
                    final boolean cancelChild = resetCancelNextUpFlag(target.child)
                            || intercepted;
                    //dispatchTransformedTouchEvent會將Event轉化為child坐標空間(getX的變化),然後去除無關的points id,如果有必要更改事件,最後調用child.dispatchTouchEvent
                    if (dispatchTransformedTouchEvent(ev, cancelChild,
                            target.child, target.pointerIdBits)) {
                        handled = true;
                    }
                    if (cancelChild) {
                        if (predecessor == null) {
                            mFirstTouchTarget = next;
                        } else {
                            predecessor.next = next;
                        }
                        target.recycle();
                        target = next;
                        continue;
                    }
                }
                predecessor = target;
                target = next;
            }
        }

        // Update list of touch targets for pointer up or cancel, if needed.
        if (canceled
                || actionMasked == MotionEvent.ACTION_UP
                || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
            resetTouchState();
        } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
            final int actionIndex = ev.getActionIndex();
            final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
            removePointersFromTouchTargets(idBitsToRemove);
        }
    }

    ... 
    //用於測試的代碼

    return handled;
}
```

事件派發流程主要集中在這幾個方法的調用:
- dispatchTouchEvent 這是事件派發每個View的時候,第一個被調用的方法,如果是ViewGroup,dispatchTouchEvent會先去調用onInterceptTouchEvent是否應該攔截事件,不攔截的話會先從子View中判斷是否有處理該次事件的(在ACTION_DOWN中采用mFirstTouchTarget鏈接保存會處理事件的TouchTarget),如果沒有的話則調用當前View的onTouchEvent。
- onInterceptTouchEvent 判斷是否應該攔截事件,ViewGroup默認實現是返回false,子View可以調用getParent.requestDisallowInterceptTouchEvent()來阻止父View攔截。否則只要有子View可能消費事件,該方法都會被調用。
- onTouchEvent這個方法是在沒有子View將會消耗事件時才會被調用,onClickListener,onTouchListener,onLongClickListener都是在這個方法中處理的。如果返回true表示消費這次事件。



對於事件派發流程,我覺得有幾個地方需要注意的:
1. 應該把ViewGroup以及它所包含的子View都看作是這個ViewGroup的一部分,對於一個ViewGroup是否會處理一次事件,應該是包含了它的子View是否也處理。
2. 如果整個ViewGroup以及它的子類沒有一個View處理ACTION_DOWN事件,那麼下一次就不會調用這個ViewGroup的dispatchTouchEvent。***但是如果ACTION_DOWN返回了true,那麼下一次事件還是會繼續派發到ViewGroup,即使中間某個ACTION_MOVE返回了false***。
3. onInterceptTouchEvent是在子View可能會處理該次事件,並且沒有被設置FLAG_DISALLOW_INTERCEPT才會被調用。正常情況下,它在ACTION_DOWN的時候一定會被調用的,因為在ACTION_DOWN的時候會先調用resetTouchState()。

源碼是解釋很多現象的最根本的原因,閱讀源碼能夠更好地理解事件派發流程,理解地更加深刻。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved