从源码角度分析Android 事件传递流程

来源:互联网 发布:网络调查平台 编辑:程序博客网 时间:2024/05/21 10:56

自从开始负责控件模块开始,我一直都想好好分析一下Android事件传递流程,相信网上有一大堆相关文章,但是我个人觉得作为一个专业的控件开发人员,如果只是知道一下大概,而不知其所以然,则不算一个合格的控件开发人员,感谢我曾经一位同事,在我刚开始接触控件的时候带着我,很耐心的教会我控件的内在,下面我个人从源码角度来分析Android事件传递流程,基于Android5.0的代码,如果有错误的地方,还望指出。如果只是想知道事件的流程,可以参考我的上一篇文章 Android事件传递分析

一,根视图内部消息派发过程
对于上层代码来说,最先处理事件的是viewRootImpl,下面先看一下viewRootImpl与TouchEvent相关的内容:

protected int onProcess(QueuedInputEvent q) {            if (q.mEvent instanceof KeyEvent) {                mKeyEventStatus = INPUT_DISPATCH_STATE_VIEW_POST_IME_STAGE;                return processKeyEvent(q);            } else {                mMotionEventStatus = INPUT_DISPATCH_STATE_VIEW_POST_IME_STAGE;                // If delivering a new non-key event, make sure the window is                // now allowed to start updating.                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);                }            }        }        private int processPointerEvent(QueuedInputEvent q) {            final MotionEvent event = (MotionEvent)q.mEvent;            mAttachInfo.mUnbufferedDispatchRequested = false;            boolean handled = mView.dispatchPointerEvent(event);            if (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) {                mUnbufferedInputDispatch = true;                if (mConsumeBatchedInputScheduled) {                    scheduleConsumeBatchedInputImmediately();                }            }            return handled ? FINISH_HANDLED : FORWARD;        }

从上面代码我们可以看出事件出传递到mView的dispatchPointerEvent方法里面,通过追踪mView,不难发现mView其实是PhoneWindow.DecorView。
而dispatchPointerEvent()是View里面的方法,如果当前事件是Touch事件则会调用当前View的dispatchTouchEvent(),再看一下PhoneWindow.DecorView dispatchTouchEvent():

  @Override        public boolean dispatchTouchEvent(MotionEvent ev) {            final Callback cb = getCallback();          //DecorView继承自FrameLayout,但FrameLayout没有重写dispatchTouchEvent,cb为空则直接执行ViewGroup.dispatchTouchEvent()            return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTouchEvent(ev)                    : super.dispatchTouchEvent(ev);        }        //CallBack 是Window的一个内部Interface,作用是可以让用户在事件的分发,菜单的构建过程中进行拦截。其中dispatchTouchEvent正是用于拦截触控事件,Activity实现了这个方法    public boolean dispatchTouchEvent(MotionEvent ev) {        if (ev.getAction() == MotionEvent.ACTION_DOWN) {            onUserInteraction();        }        if (getWindow().superDispatchTouchEvent(ev)) {            return true;        }        return onTouchEvent(ev);    }

从上面代码可以看出,getWindow().superDispatchTouchEvent(ev)为false的时候,自身的onTouchEvent()函数才会被回调。这就是为什么每次事件的都是从Activity的dispatchTouchEvent 开始,最终又会传回Activity的onTouchEvent。另外这里的getWindow()实际上返回的是PhoneWindow,下面再看看PhoneWindow相关的代码:

  @Override    public boolean superDispatchTouchEvent(MotionEvent event) {        boolean handled = mDecor.superDispatchTouchEvent(event);        return handled;    }        public boolean superDispatchTouchEvent(MotionEvent event) {            return super.dispatchTouchEvent(event);        }

从上面代码可看出,事件最后传到mDecor.superDispatchTouchEvent(),而mDecor.superDispatchTouchEvent()单单执行了超类的dispatchTouchEvent()也就是ViewGroup的dispatchTouchEvent(),之后事件被分发到布局中的View中去。上述流程图如下:
这里写图片描述
二,ViewGroup内部消息派发过程
1.ViewGroup中的dispatchTouchEvent
ViewGroup中的dispatchTouchEvent()在View中的事件传递中承担了比较重要的角色,也是精华部分。它主要承担了是三个工作:1.拦截子View事件(调用自身的onInterceptTouchEvent()) 2.找出可以接受事件的子View,并把事件传递下去 2.把交由自身的TouchEvent()处理事件。下面贴出ViewGroup中的dispatchTouchEvent()的代码:

@Override    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.               /*                ACTION_DOWN是一些列事件的开端,因此需要做一些初始化工作。这里主要实现了两点:                1.将mFirstTouchTarget设置为null                2.清除FLAG_DISALLOW_INTERCEPT,让事件可以被拦截               */            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) {               /*               1.disallowIntercept 由FLAG_DISALLOW_INTERCEPT标志位所决定,应用可以通过调用View.requestDisallowInterceptTouchEvent(boolean disallowIntercept)设置。默认为false               2.disallowIntercept为false时,onInterceptTouchEvent()会被调用,其返回值将决定事件是否会分发到其子view               3.TouchTarget是ViewGroup的内部静态类,链式结构,有相关的回收机制,用于记录当前被点击的View,以及点击的Pointer, ViewGroup的mFirstTouchTarget总指向TouchTarget的最前一个。               4.mFirstTouchTarget != null说明已经找到可以接受事件的View,通过onInterceptTouchEvent()同样可以对其进行拦截               */                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);                    full_meizu6795_lwt_l1-userdebug                    final int childrenCount = mChildrenCount;                    /*                      1.从这里开始遍历子View,遍历能采取两种方式:                         ①当isChildrenDrawingOrderEnabled()返回true,根据getChildDrawingOrder(int childCount, int i)函数的顺序遍历                            从这里可以看出,应用可以通过重写isChildrenDrawingOrderEnabled()以及getChildDrawingOrder(int childCount, int i)来指定子View的遍历顺序,isChildrenDrawingOrderEnabled()默认返回false                         ②默认情况下,采用倒序遍历子View                      2.遍历过程中,会调用dispatchTransformedTouchEvent(),把事件传到当前子View的dispatchTouchEvent()中                      3.遍历过程中,假如对某个子view执行dispatchTransformedTouchEvent()返回true,遍历被中断。同时把当前的View以及当前的TouchEvent的pointerIndex记录在mFirstTouchTarget 中                    */                    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 = 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;                            }                            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.            /*            mFirstTouchTarget == null表明没有找到可以消费事件的子view,            然后通过this.dispatchTransformedTouchEvent()——>View.dispatchTransformedTouchEvent()——>this.onTouchEvent()            流程把事件分发到自身的onTouchEvent()            */            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.                /*                当mFirstTouchTarget !=null时可能是以下几种情况:                 (1).满足条件(alreadyDispatchedToNewTouchTarget && target == newTouchTarget)也就是当前事件是Action_Down,并且通过上面的遍历找到可以消费事件的子View,则直接返回true;                 (2).不满足1条件,但是事件通过需要被拦截,或者当前可消费事件的子View暂时不可见时,向该子View派发Action_Cancel事件,如上面的case5                 (3).向当前可消费事件的子View分发事件。通常是这样的情况:找到可消费事件的子View,当前又非Action_Down事件并且当前的ViewGroup没有进行拦截。                 */                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;                        }                //cancelChild为true,说明child收到拦截,因此清理与该child相关的TouchTarget                        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;    }

其处理流程图如下:
这里写图片描述
2.ViewGroup的dispatchTransformedTouchEvent()
下面先对dispatchTransformedTouchEvent()源码进行分析:

  private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,            View child, int desiredPointerIdBits) {        final boolean handled;        // Canceling motions is a special case.  We don't need to perform any transformations        // or filtering.  The important part is the action, not the contents.        //上面分析提及到,在事件被拦截时,子View可能会接收到CANCEL事件,在这里可以看到event被直接传到子类的dispatchTouchEvent()没有作坐标转换,因此在ACTION_CANCEL事件里 面我们不应该去event的相关坐标进行计算。        final int oldAction = event.getAction();        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;        }        // Calculate the number of pointers to deliver.       //过滤触控点        final int oldPointerIdBits = event.getPointerIdBits();        final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;       // Motion事件没有对应点,则丢弃这个Motion        if (newPointerIdBits == 0) {            return false;        }        final MotionEvent transformedEvent;        if (newPointerIdBits == oldPointerIdBits) {            if (child == null || child.hasIdentityMatrix()) {                if (child == null) {                    handled = super.dispatchTouchEvent(event);                } else {                   //这里将当前的坐标重新转换到child的坐标系中                    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);        }   .....    }
从上述源码可知,dispatchTransformedTouchEvent()主要有两个作用:

1.当child为空时,把事件传递到超类也就是View的dispatchTouchEvent()中。
2.当child不为空时,事件传递到child的dispatchTouchEvent()中,但是传递之前首先把事件的对应的坐标重新转化为child坐标系中的坐标,而转换的的方法是:
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
event.offsetLocation(offsetX, offsetY);
为什么要这样转换?这里涉及两种坐标的概念:
1.视图坐标:视图坐标没有边界,它取决于View本身的大小,而不受屏幕大小的限制。
2.布局坐标:大小受限制,是指父视图给子视图分配的布局(layout)大小,超过这个大小的区域将不能显示到父视图的区域中。
上面两种坐标的关系如下图:
这里写图片描述
从上图可知道布局坐标转化为视图坐标只需要加上mScrollY/mScrollX即可。
通常我们通过event.getX()/event.getX()获取到的坐标是布局坐标,而child.mLeft,child.mRight则是相对于视图坐标而言的,因此在父视图获取获取到event的坐标后必须先转化为视图坐标,再根据child在父视图中的位置,进行坐标平移,即 event.offsetLocation(+mScrollX - offsetX, + mScrollY - offsetY).
3,View的dispatchTouchEvent()

 public boolean dispatchTouchEvent(MotionEvent event) {....        if (onFilterTouchEventForSecurity(event)) {            //noinspection SimplifiableIfStatement            ListenerInfo li = mListenerInfo;            if (li != null && li.mOnTouchListener != null                    && (mViewFlags & ENABLED_MASK) == ENABLED                    && li.mOnTouchListener.onTouch(this, event)) {                result = true;            }            if (!result && onTouchEvent(event)) {                result = true;            }        }....        return result;    }

上面给出View.dispatchTouchEvent()的主要代码,从上面代码可以看出,当mOnTouchListener不为空时会先执行mOnTouchListener.onTouch(this, event),而当mOnTouchListener没有消耗事件时onTouchEvent()才会被执行,这说明在同一个View,mOnTouchListener优先级会比onTouchEvent要高。
4,View的onTouchEvent(MotionEvent event)

 public boolean onTouchEvent(MotionEvent event) {        final float x = event.getX();        final float y = event.getY();        final int viewFlags = mViewFlags;        if ((viewFlags & ENABLED_MASK) == DISABLED) {            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {                setPressed(false);            }            // A disabled view that is clickable still consumes the touch            // events, it just doesn't respond to them.           //尽管当前View是disable状态,但是只要是CLICKABLE或者LONG_CLICKABLE仍然可以消费事件            return (((viewFlags & CLICKABLE) == CLICKABLE ||                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));        }        //如果设置代理,则事件交由代理处理,如果代理消耗了事件则直接返回true        if (mTouchDelegate != null) {            if (mTouchDelegate.onTouchEvent(event)) {                return true;            }        }        if (((viewFlags & CLICKABLE) == CLICKABLE ||                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {            switch (event.getAction()) {                case MotionEvent.ACTION_UP:               ...                        if (!mHasPerformedLongPress) {                            // This is a tap, so remove the longpress check                            removeLongPressCallback();                            // Only perform take click actions if we were in the pressed state                            if (!focusTaken) {                                // Use a Runnable and post this rather than calling                                // performClick directly. This lets other visual state                                // of the view update before click actions start.                                if (mPerformClick == null) {                                    mPerformClick = new PerformClick();                                }                              //假如对view设置了OnClickListener,在这里会被回调。                                if (!post(mPerformClick)) {                                    performClick();                                }                            }                        }              ...                    break;                case MotionEvent.ACTION_DOWN:              ...                    if (isInScrollingContainer) {                        mPrivateFlags |= PFLAG_PREPRESSED;                        if (mPendingCheckForTap == null) {                            mPendingCheckForTap = new CheckForTap();                        }                        mPendingCheckForTap.x = event.getX();                        mPendingCheckForTap.y = event.getY();                        //检查长按事件,假如设置了OnLongClickListener,在此有可能被回调                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());                    } else {                        // Not inside a scrolling container, so show the feedback right away                        setPressed(true, x, y);                         //检查长按事件,假如设置了OnLongClickListener,在此有可能被回调                        checkForLongClick(0);                    }                 ...                    break;                case MotionEvent.ACTION_CANCEL:                 ...                    break;                case MotionEvent.ACTION_MOVE:                 ...                    break;            }            return true;        }        return false;    }

从上面代码可以总结出一下几点:
1.尽管当前View是disable状态但仍然具有消费事件能力
2.假如设置了代理,事件将先交由代理处理,假如代理消费了事件,则直接返回true
3.在没有设置代理的情况下,假如标记位CLICKABLE LONG_CLICKABLE不为0,则事件必然在此被消费
4.OnLongClickListener和OnClickListener的回调函数都在View的onTouchEvent()里面执行,但执行时机有区别, OnClickListener.onClick()在ACTION_UP时被回调。OnLongClickListener.onLongClick()则在ACTION_DOWN的时候被执行(其实也不一定在这个时机被执行,因为长按需要作一定的时延检测)。另外我们在定义View时经常需要监 听点击事件,这里不推荐通过setOnClickListener()的方式实现,因为这样相当于占用了应用的监听权利,假如此时应用在不知道代码逻辑的情况下,继续setOnClickListener(),那么默认的监听器被覆盖。做成意想不到的后果。其实替代方案可以是重写performClick()。长按事件同理。
参考资料
https://www.youtube.com/watch?v=EcQRqKk7wuQ 附件中有相应的demo
http://www.cnblogs.com/sunzn/archive/2013/05/10/3064129.html
http://blog.csdn.net/stonecao/article/details/6759189
http://blog.csdn.net/xiaanming/article/details/21696315
《Android内核剖析》

0 0
原创粉丝点击