Android O Touch事件處理流程源碼分析

本篇文章主要是以Activity上的觸摸事件爲例,事件從InputReader,InputDispatcher傳到ViewRootIpml開始談起。

首先是時序圖


其中最複雜的就是ViewGroup的dispatchTouchEvent方法將事件層層分發:

public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }

        // If the event targets the accessibility focused view and this is it, start
        // normal event dispatch. Maybe a descendant is what will handle the click.
        if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
            ev.setTargetAccessibilityFocus(false);
        }

        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            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.
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            // Check for interception.
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    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<View> preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, 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;
                            }

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

            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // 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) {
                    final TouchTarget next = target.next;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        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);
            }
        }

        if (!handled && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
        }
        return handled;
    }

下面具體分析:

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

首先一個完整的touch事件是以DOWN事件開始,以UP事件結束,中間可能貫穿多個MOVE事件,這個判斷的作用是,判斷一個新事件的開始,就將ViewGroup的成員變量mFirstTouchTarget的值置爲nullmFirstTouchTarget指向的是消耗了touch事件的子View,如果沒有子View消耗事件,該成員變量的值就是null的,這個值很重要,決定着後續MOVEUP事件的傳遞流程


// Check for interception.
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    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;
            }

檢查當前ViewGroup是否調用onInterceptTouchEvent方法攔截事件,若攔截,則變量intercepted的值置爲true,否則就是false

第一個判斷actionMasked == MotionEvent.ACTION_DOWN|| mFirstTouchTarget != null的意思是:

1)如果是DOWN事件,那麼肯定走攔截的方法;

2)如果不是DOWN事件,則判斷mFirstTouchTarget是否爲null,即該ViewGroup的子View在之前的DOWN事件中是否消費了此次事件,如果消費了(即DOWN事件的onTouchEvent返回true,或者DOWN事件在dispatchTouchEvent分發的時候直接返回true),則此次非DOWN事件也會走到攔截的方法onInterceptTouchEvent中去,如果沒有消費,則直接將intercepted置爲true,不走該ViewGroup的攔截方法onInterceptTouchEvent方法,直接將intercepted置爲true


3

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);
//3.1
                    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<View> preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, 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;
                            }
//3.2
                            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);
                            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();
                                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;
                    }
                }
            }


3中首先是兩個判斷,主要就是判斷是DOWN事件,且沒有攔截(interceptedfalse)。

3.1中首先是判斷該ViewGroup有沒有child,如果沒有就沒有必要往下傳遞執行了,之後獲取下點擊的座標和所有的子View,一個for循環遍歷這個集合。注意這個循環是從ViewGroup的最上層的子View開始,依次往下遍歷。

3.2 中首先判斷子View能否接受point事件,並且這個point事件是否在這個view裏面,如果有一個不滿足,則continue,直接跳過本次循環;

然後調用dispatchTransformedTouchEvent方法,將事件在往子View分發,實現遞歸分發,知道最上層的view,如果在這個子View的某個child消費了事件(即DOWN事件的onTouchEvent返回true,或者DOWN事件在dispatchTouchEvent分發的時候直接返回true),則將newTouchTargetmFirstTouchTarget都指向給子View(注意是一層一層的指向,即ViewGroup1指向ViewGroup2ViewGroup2指向View1,而View1是真正消費事件的View),並且將alreadyDispatchedToNewTouchTarget置爲true


4 dispatchTransformedTouchEvent方法中:

if (newPointerIdBits == oldPointerIdBits) {
            if (child == null || child.hasIdentityMatrix()) {
                if (child == null) {
                    handled = super.dispatchTouchEvent(event);
                } else {
                    final float offsetX = mScrollX - child.mLeft;
                    final float offsetY = mScrollY - child.mTop;
                    event.offsetLocation(offsetX, offsetY);

                    handled = child.dispatchTouchEvent(event);

                    event.offsetLocation(-offsetX, -offsetY);
                }
                return handled;
            }
            transformedEvent = MotionEvent.obtain(event);
        } else {
            transformedEvent = event.split(newPointerIdBits);
        }

一般newPointerIdBitsoldPointerIdBits都是1child.hasIdentityMatrixtrue的,因此:

1)如果傳進來的childnull,則調用本身ViewGroup的父類ViewdispatchTouchEvent方法處理事件。此方法中最後會調用到ViewGrouponTouchEvent方法,這個後面再說。

2)如果傳進來的child不爲null,則調用childdispatchTouchEvent方法,將事件繼續往下傳遞。child如果是ViewGroup,則ViewGroup的分發dispatchTouchEvent是往子View傳遞,child如果是View,則ViewdispatchTouchEvent是調用onTouchEvent去消費它。


5

if (mFirstTouchTarget == null) {
                // 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) {
                    final TouchTarget next = target.next;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        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;
                }
            }

經過層層循環調用dispatchTouchEvent,當事件一直傳遞到最上層的View的父佈局ViewGroupdispatchTouchEvent時候,調用完3.2的代碼循環完以後,執行了每個touch點內的childdispatchTouchEventonTouchEvent方法後,執行5處的代碼,

1)首先判斷mFirstTouchTarget是否爲null,如果爲null,調用dispatchTransformedTouchEvent方法,此時調用4處代碼,執行的是該ViewGroupsuper.dispatchTouchEvent方法,內部會執行到該ViewGrouponTouchEvent方法;

2)如果mFirstTouchTarget不爲null,即某個子View消費了這個事件,則進入else分支的while循環中,判斷alreadyDispatchedToNewTouchTarget && target == newTouchTarget是否成立,這個判斷是用於區分DOWN事件和其他事件的,如果是DOWN事件,則條件滿足,將handled置爲true,如果是非DOWN事件,則進入else分支,找到這個target對應的View,調用dispatchTransformedTouchEvent向這個View分發事件。

注意:如果是Down之後的MOVE或者UP事件,執行ViewGroupdispatchTouchEvent時,執行完12以後,直接執行5處的代碼,如果之前的DOWN事件中判斷子View沒有消費掉事件,則直接執行此ViewGrouponTouchEvent方法,事件到此ViewGroup就不往下傳遞,直接返回上層調用處了,若子View消費掉事件,進入else分支,將MOVE或者DOWN事件向目標View繼續向下傳遞(即調用子ViewdispatchTouchEvent方法)。


總結:

首先一個完整的touch事件是以DOWN事件開始,以UP事件結束,中間可能貫穿多個MOVE事件。Down和後面的MoveUp事件是緊密聯繫的。

1 ViewGroup在執行dispatchTouchEvent的時候的onInterceptTouchEvent方法會不會執行到,主要是看:

1)如果是Down事件,肯定會執行到。

2)如果是Down後的Move或者Up事件,看之前的Down事件中,子View有沒有消費掉該事件,如果消費掉了該事件,則mFirstTouchTarget不爲null,纔會走onInterceptTouchEvent,如果在之前的Down事件中該ViewGroup沒有子View消費事件,則不會走到onInterceptTouchEvent,而是將intercepted直接置爲true

從這裏也可以感覺出,Down事件可以看出是否用來消費事件,爲後面的MoveUp事件做準備的。

 

2MoveUp事件不會走到3處的代碼,而是直接走到5處的代碼,判斷mFirstTouchTarget是否爲null,如果爲null,表明在之前的Down事件中,沒有子View消費事件,則進入dispatchTransformedTouchEvent方法,進入child==null的判斷,此時調用ViewGroup自身的super.dispatchTouchEvent方法,裏面會調用ViewGroup自身的onTouchEvent方法。

如果不爲null,表明在之前的Down事件中子View消費了事件,此時,走到else判斷,進入while循環中的else分支,調用dispatchTransformedTouchEvent將事件分發到消費了事件的子View處理。

 

2 對於註冊了onTouchListener , onClickListener , onLongClickListererView處理

1setOnTouchListener(),此回調是在ViewdispatchTouchEvent方法中,在onTouchEvent方法之前,會判斷有沒有註冊touch listener,如果有回調其中的onTouch方法,根據onTouch的返回值決定dispatchTouchEvent方法是否直接return

2setOnClickListener() 此回調是在ViewonTouchEvent方法中caseACTION_UP的情況下調用onClick方法,改方法沒有返回值。

3setOnLongClickListener()是在ViewonTouchEvent方法中caseACTION_DOWN情況下,發送一個延遲消息實現,在ACTION_UP中會刪除這條消息。回調onLongClick方法,該方法有返回值,返回true後,在會掉完onLongClick後的ACTION_UP事件中不回調onClick,返回false之後,在ACTION_UP事件中依舊會回調onClick方法。

注意:設置setOnClickListener()setOnLongClickListener()方法後,View在調用onTouchEvent方法時,就會局部變量clickable的值置爲true,就會走到Switch方法,根據Action類型不同操作,一旦走到Switch,最後都會return true,即onTouchEvent返回true。這裏就會影響到事件的分發。比如DOWN事件之後的MOVE UP事件都會傳遞到該View上來。















發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章