欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

从点击屏幕到事件处理的事件分发源码流程

程序员文章站 2022-05-14 15:47:33
...

从点击屏幕到事件处理的事件分发源码流程

有事没事先来张图
从点击屏幕到事件处理的事件分发源码流程

怎么打印出来的,代码先奉上
Thread.dumpStack();
在dispatchTouchEvent(MotionEvent event)方法中执行该方法

通过以上方法,可打印出从点击屏幕到执行dispatchTouchEvent(MotionEvent event)的执行流程,感觉以后分析再也不用去一个个方法去找了直接根据流程来就是了

欢迎底层大佬打脸底层萌新的我

第一个执行是ZygoteInit的main()方法感觉回到了最初学java的时候了,原来android系统也是从从main方法开始的啊

一直觉得android世界里没有main方法的呢

ZygoteInit

public static void main(String argv[]) {
    try {
        ...
    } catch (MethodAndArgsCaller caller) {
        caller.run();
    } catch (RuntimeException ex) {
        closeServerSocket();
        throw ex;
    }
}

底层的东西不敢说话,咱们直接看流程

ZygoteInit$MethodAndArgsCaller.run

public void run() {
        try {
            mMethod.invoke(null, new Object[] { mArgs });
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(ex);
        } catch (InvocationTargetException ex) {
            Throwable cause = ex.getCause();
            if (cause instanceof RuntimeException) {
                throw (RuntimeException) cause;
            } else if (cause instanceof Error) {
                throw (Error) cause;
            }
            throw new RuntimeException(ex);
        }
    }

这里执行了mMethod方法,这个mMethod通过构造方法传递赋值
new ZygoteInit.MethodAndArgsCaller(m, argv);

Method m;
    try {
        m = cl.getMethod("main", new Class[] { String[].class });
    } catch (NoSuchMethodException ex) {
        throw new RuntimeException(
                "Missing static main on " + className, ex);
    } catch (SecurityException ex) {
        throw new RuntimeException(
                "Problem getting static main on " + className, ex);
    }

这里的mThread执行了main方法,这个main方法是ActivityThread的main方法

ActivityThread

public static void main(String[] args) {
    SamplingProfilerIntegration.start();
    CloseGuard.setEnabled(false);
    Environment.initForCurrentUser();
    EventLogger.setReporter(new EventLoggingReporter());
    Security.addProvider(new AndroidKeyStoreProvider());
    Process.setArgV0("<pre-initialized>");
    //mainThread都不用自己prepare()
    Looper.prepareMainLooper();
    //居然新建自己
    ActivityThread thread = new ActivityThread();
    thread.attach(false);
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }
    AsyncTask.init();
    if (false) {
        Looper.myLooper().setMessageLogging(new
                LogPrinter(Log.DEBUG, "ActivityThread"));
    }
    //handler的looper循环
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

接下里是MessageQueue的执行,然后执行dispatchInputEvent()

InputEventReceiver

// Called from native code.
private void dispatchInputEvent(int seq, InputEvent event) {
    mSeqMap.put(event.getSequenceNumber(), seq);
    onInputEvent(event);
}

这就是底层里出来的方法,终于顺眼了
这个方法是处理分发输入事件的

public void onInputEvent(InputEvent event) {
    finishInputEvent(event, false);
}

这里有输入事件时这个方法会被调用,这里不会执行finishInputEvent()方法,而执行ViewRootImpl中的
WindowInputEventReceiver类的onInputEvent();
WindowInputEventReceiver继承了上面的InputEventReceiver

ViewRootImpl$WindowInputEventReceiver

final class WindowInputEventReceiver extends InputEventReceiver {
    public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
        super(inputChannel, looper);
    }
    @Override
    public void onInputEvent(InputEvent event) {
        enqueueInputEvent(event, this, 0, true);
    }
    @Override
    public void onBatchedInputEventPending() {
        scheduleConsumeBatchedInput();
    }
    @Override
    public void dispose() {
        unscheduleConsumeBatchedInput();
        super.dispose();
    }
}

接着执行enqueueInpoutEvent()

ViewRootImpl

void enqueueInputEvent(InputEvent event,
        InputEventReceiver receiver, int flags, boolean processImmediately) {
    QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
    QueuedInputEvent last = mPendingInputEventTail;
    if (last == null) {
        mPendingInputEventHead = q;
        mPendingInputEventTail = q;
    } else {
        last.mNext = q;
        mPendingInputEventTail = q;
    }
    mPendingInputEventCount += 1;
    Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
            mPendingInputEventCount);
    //是否立即执行
    if (processImmediately) {
        doProcessInputEvents();
    } else {
        scheduleProcessInputEvents();
    }
}

接着doProcessInputEvents();

void doProcessInputEvents() {
    // Deliver all pending input events in the queue.
    while (mPendingInputEventHead != null) {
        QueuedInputEvent q = mPendingInputEventHead;
        mPendingInputEventHead = q.mNext;
        if (mPendingInputEventHead == null) {
            mPendingInputEventTail = null;
        }
        q.mNext = null;
        mPendingInputEventCount -= 1;
        Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
                mPendingInputEventCount);
        //交付处理输入事件
        deliverInputEvent(q);
    }
    // 完成了所有输入事件的处理清除标志
    if (mProcessInputEventsScheduled) {
        mProcessInputEventsScheduled = false; 
        mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
    }
}

接着deliverInputEvent();

private void deliverInputEvent(QueuedInputEvent q) {
    Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent");
    try {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);
        }
        //处理输入事件的阶段基类
        InputStage stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
        if (stage != null) {
            //输入阶段交付处理
            stage.deliver(q);
        } else {
            finishInputEvent(q);
        }
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_VIEW);
    }
}

ViewRootImpl$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));
        }
    }

接着apply();

//将事件应用到指定的事件
protected void apply(QueuedInputEvent q, int result) {
        if (result == FORWARD) {
            forward(q);
        } else if (result == FINISH_HANDLED) {
            finish(q, true);
        } else if (result == FINISH_NOT_HANDLED) {
            finish(q, false);
        } else {
            throw new IllegalArgumentException("Invalid result: " + result);
        }
    }

接着forward(q);

    //将事件向下一阶段抛出
    protected void forward(QueuedInputEvent q) {
        onDeliverToNext(q);
    }

接着onDeliverToNext();

    protected void onDeliverToNext(QueuedInputEvent q) {
        if (mNext != null) {
            //下一阶段接着处理
            mNext.deliver(q);
        } else {
            finishInputEvent(q);
        }
    }

接着又交付处理deliver(q),执行apply()方法,这里的apply()是子类的方法

ViewRootImpl$AsyncInputStage

AsyncInputStage可实现异步处理事件也是顺序处理阶段的基类

@Override
    protected void apply(QueuedInputEvent q, int result) {
        if (result == DEFER) {
            defer(q);
        } else {
            super.apply(q, result);
        }
    }

接着又执行父类的apply方法即InputStage的apply(),又执行AsyncInputStage的forward()

@Override
    protected void forward(QueuedInputEvent q) {
        //清除延迟标志
        q.mFlags &= ~QueuedInputEvent.FLAG_DEFERRED;
        // 如果队列为空,则重来
        QueuedInputEvent curr = mQueueHead;
        if (curr == null) {
            super.forward(q);
            return;
        }
        // 确定事件在传递到下一阶段之前是否进行序列化
        final int deviceId = q.mEvent.getDeviceId();
        QueuedInputEvent prev = null;
        boolean blocked = false;
        while (curr != null && curr != q) {
            if (!blocked && deviceId == curr.mEvent.getDeviceId()) {
                blocked = true;
            }
            prev = curr;
            curr = curr.mNext;
        }
        //如果阻塞了会放到队列中稍后处理,如果延迟了也可能没有放入队列中
        if (blocked) {
            if (curr == null) {
                enqueue(q);
            }
            return;
        }
        //事件没有阻止立即移交处理
        if (curr != null) {
            curr = curr.mNext;
            dequeue(q, prev);
        }
        super.forward(q);
        while (curr != null) {
            if (deviceId == curr.mEvent.getDeviceId()) {
                if ((curr.mFlags & QueuedInputEvent.FLAG_DEFERRED) != 0) {
                    break;
                }
                QueuedInputEvent next = curr.mNext;
                dequeue(curr, prev);
                super.forward(curr);
                curr = next;
            } else {
                prev = curr;
                curr = curr.mNext;
            }
        }
    }

接着执行了父类的forward()方法,接着顺讯执行了父类的onDeliverToNext()、deliver(),最后执行ViewPostImeInputStage.onProcess(),ViewPostImeInputStage也继承了InputStage

ViewRootImpl$ViewPostImeInputStage

@Override
    protected int onProcess(QueuedInputEvent q) {
        if (q.mEvent instanceof KeyEvent) {
            return processKeyEvent(q);
        } else {
            //如果交付了一个新的非键事件,确保window现在允许更新
            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);
            }
        }
    }

接着processPointerEvent(q)开始处理事件分发了

private int processPointerEvent(QueuedInputEvent q) {
        final MotionEvent event = (MotionEvent)q.mEvent;
        //这里的mView就是decorView,在ViewRootImpl中的setView中被赋值,
        //了解源码知道在Activity的makeVisible方法系列流程中在windowMangerGlobal中会new ViewRootImpl并会调用setView方法
        if (mView.dispatchPointerEvent(event)) {
            return FINISH_HANDLED;
        }
        return FORWARD;
    }

接着执行View的dispatchPointerEvent()

View

public final boolean dispatchPointerEvent(MotionEvent event) {
    //是否触摸事件
    if (event.isTouchEvent()) {
        return dispatchTouchEvent(event);
    } else {
        return dispatchGenericMotionEvent(event);
    }
}

接下里执行的decorView的dispatchTouchEvent()

PhoneWindow$DecorView

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //这执行了回调的dispatchTouchEvent()
        final Callback cb = getCallback();
        return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTouchEvent(ev)
                : super.dispatchTouchEvent(ev);
    }

这里的CallBack是Window的Callback接口,而Activitiy实现了Window的Callback接口,这个cb.dispatchTouchEvent()也就执行了Activity的dispatchTouchEvent()

Activity

//这个也就我们在activity中使用的dispatchTouchEveent()
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        onUserInteraction();
    }
    if (getWindow().superDispatchTouchEvent(ev)) {
        return true;
    }
    return onTouchEvent(ev);
}

接着执行了getWindow().superDispatchTouchEvent()
window是一个接口,它的实现类是PhoneWindow

PhoneWindow

@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
    //又交给了decorView
    return mDecor.superDispatchTouchEvent(event);
}

PhoneWindw$DecorView

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

ViewGroup

//处理事件的分发
public boolean dispatchTouchEvent(MotionEvent event) {
    //检查触摸事件
    if (mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onTouchEvent(event, 0);
    }
    if (onFilterTouchEventForSecurity(event)) {
        //noinspection SimplifiableIfStatement
        ListenerInfo li = mListenerInfo;
        //onTouchListener级别高于onTouchEvent()
        if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
                && li.mOnTouchListener.onTouch(this, event)) {
            return true;
        }
        if (onTouchEvent(event)) {
            return true;
        }
    }
    if (mInputEventConsistencyVerifier != null) {
      mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
    }
    return false;

接着dispatchTransformedTouchEvent()

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
        View child, int desiredPointerIdBits) {
    final boolean handled;

    // 获取动作,重要的是动作,不是内容
    final int oldAction = event.getAction();
    if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
        event.setAction(MotionEvent.ACTION_CANCEL);
        //如果子类为空,执行父类的dispatchhTouchEvent
        if (child == null) {
            handled = super.dispatchTouchEvent(event);
        } else {
            不为空执行子类的
            handled = child.dispatchTouchEvent(event);
        }
        event.setAction(oldAction);
        return handled;
    }
    final int oldPointerIdBits = event.getPointerIdBits();
    final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
    //由于某些原因事件没有pointer
    if (newPointerIdBits == 0) {
        return false;
    }
    final MotionEvent transformedEvent;
    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);
    }
    if (child == null) {
        handled = super.dispatchTouchEvent(transformedEvent);
    } else {
        final float offsetX = mScrollX - child.mLeft;
        final float offsetY = mScrollY - child.mTop;
        transformedEvent.offsetLocation(offsetX, offsetY);
        if (! child.hasIdentityMatrix()) {
            transformedEvent.transform(child.getInverseMatrix());
        }
        handled = child.dispatchTouchEvent(transformedEvent);
    }
    transformedEvent.recycle();
    return handled;
}

流程到这里就结束了直到处理事件

总结一下,

1.由底层触发传递给MainThread,由MainThread交给ViewRootImpl的InputStage处理分发输入事件
2.—>View.dispatchPointerEvent
3.—>PhoneWindow.DecorView.dispatchTouchEvent()
4.—>Activity.dispatchTouchEvent()
5.—>PhoneWindow.superDispatchTouchEvent()
6.—>PhoneWindow.DecorView.superDispatchTouchEvent()
7.—>ViewGroup.dispatchTouchEvent()

相关标签: 事件分发