美文网首页
Android IMS原理解析之dispatchEvent

Android IMS原理解析之dispatchEvent

作者: 雷涛赛文 | 来源:发表于2021-08-28 10:39 被阅读0次

       上篇文章从整体上介绍了事件处理的流程Android IMS原理解析之processEvent,本篇文章将详细介绍事件的处理过程;

Event处理

       前面分析到,InputDispatcher将触摸事件通过InputChannel发送到目标窗口的接收方WindowInputEventReceiver的dispatchInputEvent(),接下来经过一系列调用会最终调用到ViewPostImeInputStage的processKeyEvent()处理keyEvent、调用processPointerEvent()处理MotionEvent;接下来就一起来看一下对应事件的处理逻辑:

1.processKeyEvent()

       此方法主要处理key事件比如:BACK、MENU、HOME等事件:

private int processKeyEvent(QueuedInputEvent q) {
    final KeyEvent event = (KeyEvent)q.mEvent;
    ......

    // Deliver the key to the view hierarchy.
    if (mView.dispatchKeyEvent(event)) {
         return FINISH_HANDLED;
    }
    .......
}

       本文主要分析mView.dispatchKeyEvent(event),针对activity及back键来进行分析,mView对应Activity的DecorView,看一下DecorView内部的dispatchKeyEvent()方法:

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    final int keyCode = event.getKeyCode();
    final int action = event.getAction();
    final boolean isDown = action == KeyEvent.ACTION_DOWN;
    ........
    if (!mWindow.isDestroyed()) {
        final Window.Callback cb = mWindow.getCallback();
        final boolean handled = cb != null && mFeatureId < 0 ? cb.dispatchKeyEvent(event)
                    : super.dispatchKeyEvent(event);
        if (handled) {
            return true;
        }
    }

    return isDown ? mWindow.onKeyDown(mFeatureId, event.getKeyCode(), event)
                : mWindow.onKeyUp(mFeatureId, event.getKeyCode(), event);
}

       mWindow对应着Activity的PhoneWindow,mWindow.getCallback()会返回Activity本身,该处是在Activity的attach()内部执行以下逻辑来执行赋值的,

//Activity.java
final void attach(xxxx) {
    ......
    mWindow = new PhoneWindow(this, window, activityConfigCallback);
    mWindow.setCallback(this);
    ......
}

       接着上面的分析,callback不为null,featureId为-1(所有Activity的featureId都是默认为-1),所以会执行cb.dispatchKeyEvent()即Activity的dispatchKeyEvent():

public boolean dispatchKeyEvent(KeyEvent event) {
    onUserInteraction();
    ....
    Window win = getWindow();
    if (win.superDispatchKeyEvent(event)) {
        return true;
    }

    View decor = mDecor;
    if (decor == null) decor = win.getDecorView();
    return event.dispatch(this, decor != null
                ? decor.getKeyDispatcherState() : null, this);
}

       执行event.dispatch(),对应到KeyEvent里面的dispatch()方法:

public final boolean dispatch(Callback receiver, DispatcherState state,
            Object target) {
    switch (mAction) {
        case ACTION_DOWN: {
            mFlags &= ~FLAG_START_TRACKING;
            boolean res = receiver.onKeyDown(mKeyCode, this);
            .....
            return res;
        case ACTION_UP:
            return receiver.onKeyUp(mKeyCode, this);
        .......
    }
    return false;
}

       receiver是Activity,所以会执行Activity内部的onKeyDown()及onKeyUp()方法:

public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        .....
        onBackPressed();
    }
        return true;
    }
    .....
    ......
}

public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (getApplicationInfo().targetSdkVersion
                >= Build.VERSION_CODES.ECLAIR) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
                    && !event.isCanceled()) {
            onBackPressed();
            return true;
        }
    }
    return false;
}

       所以在Activity界面收到Back事件后,会回调Activty的onBackPressed()方法,默认在onBackPressed()内部关闭activity,如果不想关闭可以重写onBackPressed()或onKeyDown()等,都能实现;
       以上就是针对在Activity界面执行Back键时processKeyEvent()的整个执行过程。
       用一张流程图总结一下:


BackKey处理流程.png
2.processPointerEvent()
private int processPointerEvent(QueuedInputEvent q) {
    final MotionEvent event = (MotionEvent)q.mEvent;
    handled = mView.dispatchPointerEvent(event);
    ......       
    return handled ? FINISH_HANDLED : FORWARD;
}

       在processPointerEvent()内部调用的是mView.dispatchPointerEvent(event),即DecorView的dispatchPointEvent(),该方法是在View.java内部,一起看一下:

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

       本文只分析MotionEvent的对应的touch事件,在dispatchPointerEvent()内部会执行dispatchTouchEvent():

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

       前面分析到,mWindow.getCallback()为activity,mFeatureId为-1,所以最终执行的是cb.dispatchTouchEvent(ev),即Activity的dispatchTouchEvent(ev):

//Activity.java
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(),先看一下PhoneWindow的superDispatchTouchEvent(ev)方法:

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

       在PhoneWindow内部的superDispatchTouchEvent()执行了DecorView的superDispatchTouchEvent(),又回到DecorView:

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

       在DecorView内部调用父类的dispatchTouchEvent,即ViewGroup的dispatchTouchEvent():

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
       ......
        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;
            .......
            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 (!canceled && !intercepted) {
                .......
               dispatchTransformedTouchEvent(en, false, child, x);
            }
        .....
        return handled;
    }

       该方法逻辑实现比较长,本文就只拿关键的地方来进行分析,主要有两点:
       1.通过onInterceptTouchEvent()来判断是否对事件进行拦截,比如:如果ViewGroup想拦截事件,可以重写onInterceptTouchEvent()来返回true,默认返回false;
       2.如果ViewGroup没有对事件进行拦截,那么会从ViewGroup的所有child View里面找到匹配的目标view执行dispatchTransformedTouchEvent()来对事件进行处理,在dispatchTransformedTouchEvent()内部会调用child的dispatchTouchEvent()来对Event进行处理;

//View.java
public boolean dispatchTouchEvent(MotionEvent event) {
    .......
    boolean result = false;
    if (onFilterTouchEventForSecurity(event)) {
        ......
        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;
}

       该方法内部主要有两项重点:
       1.先判断View(控件)是否实现了mOnTouchListener,如果没实现,直接跳过;否则判断onTouch()返回值,如果返回true,则result为true,如果返回false,则result为false;
       2.如果满足result为false,则执行onTouchEvent(event);

public boolean onTouchEvent(MotionEvent event) {
    final float x = event.getX();
    final float y = event.getY();
    final int viewFlags = mViewFlags;
    final int action = event.getAction();

    final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;

    .......

    if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
        switch (action) {
            case MotionEvent.ACTION_UP:
                ......
                if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                     // This is a tap, so remove the longpress check
                     removeLongPressCallback();

                    // Only perform take click actions if we were in the pressed state
                    if (!focusTaken) {
                        if (mPerformClick == null) {
                            mPerformClick = new PerformClick();
                        }
                        if (!post(mPerformClick)) {
                             performClick();
                        }
                     }
               }
               ......
               break;

            case MotionEvent.ACTION_DOWN:
                    
                mHasPerformedLongPress = false;

                .......
                checkForLongClick(0, x, y);
                break;

               .........
            }
            return true;
        }

    return false;
 }

       在onTouchEvent()内部逻辑处理如下,只分析DOWN和UP事件,先看DOWN事件:
       因为在DOWN时,可能会出现长按不放的情况,那么就会触发LongClick事件,执行checkForLongClick(0, x, y)来进行判断:

    private void checkForLongClick(int delayOffset, float x, float y) {
        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
            mHasPerformedLongPress = false;

            if (mPendingCheckForLongPress == null) {
                mPendingCheckForLongPress = new CheckForLongPress();
            }
            mPendingCheckForLongPress.setAnchor(x, y);
            mPendingCheckForLongPress.rememberWindowAttachCount();
            mPendingCheckForLongPress.rememberPressedState();
            postDelayed(mPendingCheckForLongPress,
                    ViewConfiguration.getLongPressTimeout() - delayOffset);
        }
    }
    private final class CheckForLongPress implements Runnable {

        @Override
        public void run() {
            if ((mOriginalPressedState == isPressed()) && (mParent != null)
                    && mOriginalWindowAttachCount == mWindowAttachCount) {
                if (performLongClick(mX, mY)) {
                    mHasPerformedLongPress = true;
                }
            }
        }

       ......
    }
    public boolean performLongClick(float x, float y) {
        mLongClickX = x;
        mLongClickY = y;
        final boolean handled = performLongClick();
        mLongClickX = Float.NaN;
        mLongClickY = Float.NaN;
        return handled;
    }
    public boolean performLongClick() {
        return performLongClickInternal(mLongClickX, mLongClickY);
    }
   private boolean performLongClickInternal(float x, float y) {
        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);

        boolean handled = false;
        final ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnLongClickListener != null) {
            handled = li.mOnLongClickListener.onLongClick(View.this);
        }
        ......
        if (handled) {
            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        }
        return handled;
    }

       通过以上调用流程可以看到,最终返回的值由是OnLongClickListener的onLongClick()来决定,如果返回true的话,那么在CheckForLongPress里面会设置mHasPerformedLongPress为true,如果返回false的话,那么mHasPerformedLongPress还是false;
       接下来分析Up事件,我们知道onClick()就是在Up后进行处理的,一起看一下UP事件处理:

case MotionEvent.ACTION_UP:
    if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
        // This is a tap, so remove the longpress check
        removeLongPressCallback();

        // Only perform take click actions if we were in the pressed state
       if (!focusTaken) {
           if (mPerformClick == null) {
               mPerformClick = new PerformClick();
           }
           if (!post(mPerformClick)) {
               performClick();
           }
       }
    }

       如果先处理的onLongClick()且返回true,那么mHasPerformedLongPress值为true,那么就不会处理后续事件了,如果返回false,那么mHasPerformedLongPress为false,那么就会执行post(mPerformClick),一起看一下执行逻辑:

private final class PerformClick implements Runnable {
    @Override
    public void run() {
        performClick();
    }
}
public boolean performClick() {
    final boolean result;
    final ListenerInfo li = mListenerInfo;
    if (li != null && li.mOnClickListener != null) {
        playSoundEffect(SoundEffectConstants.CLICK);
        li.mOnClickListener.onClick(this);
        result = true;
    } else {
        result = false;
    }
    return result;
}

       通过上面可以看到,在performClick()里面会执行OnClickListener的onClick()方法,onClick事件也就分析完了;
       用一张流程图总结一下:

MotionEvent处理流程.png
       简单总结:
       1.在Motion事件传递时,传递顺序为:DecorView-->Activity-->PhoneWindow-->DecorView-->ViewGroup-->Child View;
       2.在ViewGroup可以对事件进行拦截,如果不拦截的话,会遍历所有子view来找到目标view执行dispatchTouchEvent()响应事件;
       3.在dispatchTouchEvent()内部执行顺序为:OnTouchListenter.onTouch()-->onTouchEvent();
       4.在onTouchEvent()内部处理DOWN和UP事件,DOWN事件里面会最终执行onLongClick()回调,UP事件里面会最终执行onClick()回调,如果onLongClick()返回true,那么onClick()就不会回调了,反之回调;
       至此,IMS从事件接收到发送到处理就完成了。

相关文章

网友评论

      本文标题:Android IMS原理解析之dispatchEvent

      本文链接:https://www.haomeiwen.com/subject/mweuiltx.html