Android应用处理MotionEvent的过程

基于Android 7.0源码分析

应用收到Motion事件传递至Activity的过程

应用对于Motion事件的处理比较复杂,不同类型的事件处理方式不同:

  • Down事件 直接处理
  • Move事件 对于大多数Move事件,结合绘制过程处理,当应用收到Vsync时,处理一批Move事件(Move事件之间的间隔通常小于16ms)
  • Up事件 直接处理

直接处理事件的流程(Down事件为例)

下面从应用UI线程的Looper开始分析

int Looper::pollInner(int timeoutMillis) {
    ......
    // 从此唤醒
    int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
    ......
    for (int i = 0; i < eventCount; i++) {
        int fd = eventItems[i].data.fd;
        uint32_t epollEvents = eventItems[i].events;
        if (fd == mWakeEventFd) {
            if (epollEvents & EPOLLIN) {
                awoken();
            } else {
                ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
            }
        } else {
            ssize_t requestIndex = mRequests.indexOfKey(fd);
            if (requestIndex >= 0) {
                int events = 0;
                if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
                if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
                if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
                if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
                // 找到InputChannel的fd对应的Request,封装成Response
                // Request在应用启动注册InputChannel时添加
                pushResponse(events, mRequests.valueAt(requestIndex));
            } else {
                ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
                        "no longer registered.", epollEvents, fd);
            }
        }
    }
    ......
    // Invoke all response callbacks.
    for (size_t i = 0; i < mResponses.size(); i++) {
        Response& response = mResponses.editItemAt(i);
        if (response.request.ident == POLL_CALLBACK) {
            int fd = response.request.fd;
            int events = response.events;
            void* data = response.request.data;
#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
            ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
                    this, response.request.callback.get(), fd, events, data);
#endif
            // Invoke the callback.  Note that the file descriptor may be closed by
            // the callback (and potentially even reused) before the function returns so
            // we need to be a little careful when removing the file descriptor afterwards.
            // 调用回调的handleEvent方法,这里callback为NativeInputEventReceiver
            int callbackResult = response.request.callback->handleEvent(fd, events, data);
            if (callbackResult == 0) {
                removeFd(fd, response.request.seq);
            }

            // Clear the callback reference in the response structure promptly because we
            // will not clear the response vector itself until the next poll.
            response.request.callback.clear();
            result = POLL_CALLBACK;
        }
    }
    return result;
}

下面看NativeInputEventReceiverhandleEvent()

int NativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) {
    ......
    if (events & ALOOPER_EVENT_INPUT) {
        JNIEnv* env = AndroidRuntime::getJNIEnv();
        // 处理InputDispatcher发送的输入事件
        status_t status = consumeEvents(env, false /*consumeBatches*/, -1, NULL);
        mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");
        return status == OK || status == NO_MEMORY ? 1 : 0;
    }
    ......
}

status_t NativeInputEventReceiver::consumeEvents(JNIEnv* env,
        bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) {
    // consumeBatches为false
    if (consumeBatches) {
        mBatchedInputEventPending = false;
    }
    // outConsumedBatch为NULL
    if (outConsumedBatch) {
        *outConsumedBatch = false;
    }

    ScopedLocalRef receiverObj(env, NULL);
    bool skipCallbacks = false;
    for (;;) {
        uint32_t seq;
        InputEvent* inputEvent;
        // 读取输入事件到inputEvent中,对于Down事件status为OK(0)
        status_t status = mInputConsumer.consume(&mInputEventFactory,
                consumeBatches, frameTime, &seq, &inputEvent);
        ......
        if (!skipCallbacks) {
            ......
            jobject inputEventObj;
            switch (inputEvent->getType()) {
            ......
            case AINPUT_EVENT_TYPE_MOTION: {
                if (kDebugDispatchCycle) {
                    ALOGD("channel '%s' ~ Received motion event.", getInputChannelName());
                }
                MotionEvent* motionEvent = static_cast(inputEvent);
                if ((motionEvent->getAction() & AMOTION_EVENT_ACTION_MOVE) && outConsumedBatch) {
                    *outConsumedBatch = true;
                }
                // 创建Java层的MotionEvent对象及其对应的Native层的MotionEvent对象,返回JNI本地引用
                inputEventObj = android_view_MotionEvent_obtainAsCopy(env, motionEvent);
                break;
            }
            ......
            }

            if (inputEventObj) {
                if (kDebugDispatchCycle) {
                    ALOGD("channel '%s' ~ Dispatching input event.", getInputChannelName());
                }
                // 调用Java层WindowInputEventReceiver(继承自InputEventReceiver)的dispatchInputEvent方法
                env->CallVoidMethod(receiverObj.get(),
                        gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj);
                if (env->ExceptionCheck()) {
                    ALOGE("Exception dispatching input event.");
                    skipCallbacks = true;
                }
                env->DeleteLocalRef(inputEventObj);
            } else {
                ALOGW("channel '%s' ~ Failed to obtain event object.", getInputChannelName());
                skipCallbacks = true;
            }
        }
        ......
    }
}

思考:Native线程如何才能调用Java?原理是什么?

对于InputEventReceiverdispatchInputEvent()处理流程,在后文中分析。

下面看InputConsumerconsume()实现

status_t InputConsumer::consume(InputEventFactoryInterface* factory,
        bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
    *outSeq = 0;
    *outEvent = NULL;

    // Fetch the next input message.
    // Loop until an event can be returned or no additional events are received.
    // 循环读取事件直到读取到特定的事件或者没有事件可读
    while (!*outEvent) {
        if (mMsgDeferred) {
            // mMsg contains a valid input message from the previous call to consume
            // that has not yet been processed.
            mMsgDeferred = false;
        } else {
            // Receive a fresh message.
            // 读取Down事件放入InputMessage中,result为OK
            status_t result = mChannel->receiveMessage(&mMsg);
            ......
        }

        switch (mMsg.header.type) {
        ......
        case AINPUT_EVENT_TYPE_MOTION: {
            // 查找事件所属Batch,对于Down事件无Batch
            ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
            ......
            // 创建MotionEvent
            MotionEvent* motionEvent = factory->createMotionEvent();
            if (! motionEvent) return NO_MEMORY;
            // 更新TouchState,与Touch resample相关
            updateTouchState(&mMsg);
            // InputMessage初始化MotionEvent
            initializeMotionEvent(motionEvent, &mMsg);
            *outSeq = mMsg.body.motion.seq;
            *outEvent = motionEvent;
            break;
        }
        }
    }
    return OK;
}

对于Down事件等直接处理的事件,处理过程相对简单,下面看Batch事件的处理过程。

Move事件作为Batch处理的流程

Batch的第一个Move事件的处理

下面从NativeInputEventReceiverconsumeEvents()开始分析。

status_t NativeInputEventReceiver::consumeEvents(JNIEnv* env,
        bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) {
    // consumeBatches为false
    if (consumeBatches) {
        mBatchedInputEventPending = false;
    }
    // outConsumedBatch为NULL
    if (outConsumedBatch) {
        *outConsumedBatch = false;
    }

    ScopedLocalRef receiverObj(env, NULL);
    bool skipCallbacks = false;
    for (;;) {
        uint32_t seq;
        InputEvent* inputEvent;
        // 读取Move事件,返回status为WOULD_BLOCK
        status_t status = mInputConsumer.consume(&mInputEventFactory,
                consumeBatches, frameTime, &seq, &inputEvent);
        if (status) {
            if (status == WOULD_BLOCK) {
                if (!skipCallbacks && !mBatchedInputEventPending
                        && mInputConsumer.hasPendingBatch()) {
                    // There is a pending batch.  Come back later.
                    if (!receiverObj.get()) {
                        receiverObj.reset(jniGetReferent(env, mReceiverWeakGlobal));
                        if (!receiverObj.get()) {
                            ALOGW("channel '%s' ~ Receiver object was finalized "
                                    "without being disposed.", getInputChannelName());
                            return DEAD_OBJECT;
                        }
                    }
                    // 防止Batch的后续Move事件再次请求
                    mBatchedInputEventPending = true;
                    if (kDebugDispatchCycle) {
                        ALOGD("channel '%s' ~ Dispatching batched input event pending notification.",
                                getInputChannelName());
                    }
                    // 调用WindowInputEventReceiver(继承自InputEventReceiver)的dispatchBatchedInputEventPending方法,请求Vsync到来时处理Batch事件
                    env->CallVoidMethod(receiverObj.get(),
                            gInputEventReceiverClassInfo.dispatchBatchedInputEventPending);
                }
                return OK;
                ......
            }
            ......
        }
    }
}

status_t InputConsumer::consume(InputEventFactoryInterface* factory,
        bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
    // consumeBatches为false
    ......
    *outSeq = 0;
    *outEvent = NULL;

    // Fetch the next input message.
    // Loop until an event can be returned or no additional events are received.
    while (!*outEvent) {
        if (mMsgDeferred) {
            // mMsg contains a valid input message from the previous call to consume
            // that has not yet been processed.
            mMsgDeferred = false;
        } else {
            // Receive a fresh message.
            // 读取Move事件
            status_t result = mChannel->receiveMessage(&mMsg);
            if (result) {
                // 通常第二次读取事件,result为WOULD_BLOCK
                // Consume the next batched event unless batches are being held for later.
                if (consumeBatches || result != WOULD_BLOCK) {
                    result = consumeBatch(factory, frameTime, outSeq, outEvent);
                    if (*outEvent) {
#if DEBUG_TRANSPORT_ACTIONS
                        ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
                                mChannel->getName().string(), *outSeq);
#endif
                        break;
                    }
                }
                // 返回WOULD_BLOCK
                return result;
            }
        }

        switch (mMsg.header.type) {
        ......
        case AINPUT_EVENT_TYPE_MOTION: {
            // 对于Batch的首个Move事件,batchIndex返回-1
            ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
            ......
            // Start a new batch if needed.
            if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
                    || mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
                // 创建新的Batch,Move事件添加到Batch
                mBatches.push();
                Batch& batch = mBatches.editTop();
                batch.samples.push(mMsg);
#if DEBUG_TRANSPORT_ACTIONS
                ALOGD("channel '%s' consumer ~ started batch event",
                        mChannel->getName().string());
#endif
                break;
            }
            ......
        }
        ......
        }
    }
    return OK;
}

对于Batch的首个Move事件,创建新的Batch,Move事件添加到Batch,然后循环读取,通常返回WOULD_BLOCK(无事件可读)。最终调用WindowInputEventReceiverdispatchBatchedInputEventPending()

    // Called from native code.
    @SuppressWarnings("unused")
    private void dispatchBatchedInputEventPending() {
        onBatchedInputEventPending();
    }

    @Override
    public void onBatchedInputEventPending() {
        // 通常mUnbufferedInputDispatch为false
        if (mUnbufferedInputDispatch) {
            super.onBatchedInputEventPending();
        } else {
            // 向Choreographer添加CALLBACK_INPUT类型的回调
            scheduleConsumeBatchedInput();
        }
    }

    void scheduleConsumeBatchedInput() {
        if (!mConsumeBatchedInputScheduled) {
            mConsumeBatchedInputScheduled = true;
            // 当Vsync到来时,回调mConsumedBatchedInputRunnable
            mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
                    mConsumedBatchedInputRunnable, null);
        }
    }
  • Choreographer 负责接收显示子系统分发的Vsync信号,协调动画、输入以及绘制

下面看Vsync到来之前,Batch的后续Move事件的处理。

Batch的后续Move事件的处理

下面仍然从NativeInputEventReceiverconsumeEvents()开始分析

status_t NativeInputEventReceiver::consumeEvents(JNIEnv* env,
        bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) {
    ......
    // consumeBatches为false
    if (consumeBatches) {
        mBatchedInputEventPending = false;
    }
    // outConsumedBatch为null
    if (outConsumedBatch) {
        *outConsumedBatch = false;
    }

    ScopedLocalRef receiverObj(env, NULL);
    bool skipCallbacks = false;
    for (;;) {
        uint32_t seq;
        InputEvent* inputEvent;
        // 读取事件
        status_t status = mInputConsumer.consume(&mInputEventFactory,
                consumeBatches, frameTime, &seq, &inputEvent);
        // 这里status为WOULD_BLOCK
        if (status) {
            if (status == WOULD_BLOCK) {
                // mBatchedInputEventPending在Batch的首个Move事件处理时设为true
                if (!skipCallbacks && !mBatchedInputEventPending
                        && mInputConsumer.hasPendingBatch()) {
                    // There is a pending batch.  Come back later.
                    if (!receiverObj.get()) {
                        receiverObj.reset(jniGetReferent(env, mReceiverWeakGlobal));
                        if (!receiverObj.get()) {
                            ALOGW("channel '%s' ~ Receiver object was finalized "
                                    "without being disposed.", getInputChannelName());
                            return DEAD_OBJECT;
                        }
                    }

                    mBatchedInputEventPending = true;
                    if (kDebugDispatchCycle) {
                        ALOGD("channel '%s' ~ Dispatching batched input event pending notification.",
                                getInputChannelName());
                    }
                    env->CallVoidMethod(receiverObj.get(),
                            gInputEventReceiverClassInfo.dispatchBatchedInputEventPending);
                    if (env->ExceptionCheck()) {
                        ALOGE("Exception dispatching batched input events.");
                        mBatchedInputEventPending = false; // try again later
                    }
                }
                // 直接返回
                return OK;
            }
        ......
        }
    }
}

status_t InputConsumer::consume(InputEventFactoryInterface* factory,
        bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
    ......
    *outSeq = 0;
    *outEvent = NULL;

    // Fetch the next input message.
    // Loop until an event can be returned or no additional events are received.
    while (!*outEvent) {
        if (mMsgDeferred) {
            // mMsg contains a valid input message from the previous call to consume
            // that has not yet been processed.
            mMsgDeferred = false;
        } else {
            // Receive a fresh message.
            // 读取InputMessage,有事件返回OK,再次读取往往返回WOULD_BLOCK
            status_t result = mChannel->receiveMessage(&mMsg);
            if (result) {
                // Consume the next batched event unless batches are being held for later.
                if (consumeBatches || result != WOULD_BLOCK) {
                    result = consumeBatch(factory, frameTime, outSeq, outEvent);
                    if (*outEvent) {
#if DEBUG_TRANSPORT_ACTIONS
                        ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
                                mChannel->getName().string(), *outSeq);
#endif
                        break;
                    }
                }
                return result;
            }
        }
        switch (mMsg.header.type) {
        ......
        case AINPUT_EVENT_TYPE_MOTION: {
            // 查找Move事件所属的Batch
            ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
            if (batchIndex >= 0) {
                // 添加后续Move事件到Batch
                Batch& batch = mBatches.editItemAt(batchIndex);
                if (canAddSample(batch, &mMsg)) {
                    batch.samples.push(mMsg);
#if DEBUG_TRANSPORT_ACTIONS
                    ALOGD("channel '%s' consumer ~ appended to batch event",
                            mChannel->getName().string());
#endif
                // while循环继续读取
                    break;
                } else {
                    // We cannot append to the batch in progress, so we need to consume
                    // the previous batch right now and defer the new message until later.
                    mMsgDeferred = true;
                    // 通常,当Up事件到来时,不能添加到Batch,如果有先前的Batch事件,立即处理
                    status_t result = consumeSamples(factory,
                            batch, batch.samples.size(), outSeq, outEvent);
                    mBatches.removeAt(batchIndex);
                    if (result) {
                        return result;
                    }
#if DEBUG_TRANSPORT_ACTIONS
                    ALOGD("channel '%s' consumer ~ consumed batch event and "
                            "deferred current event, seq=%u",
                            mChannel->getName().string(), *outSeq);
#endif
                    break;
                }
            }
            ......
        }
        ......
        }
    }
}

Batch的后续Move事件的处理相对简单,只是将Move事件添加到Batch,下面分析Vsync信号到来后,Batch事件的处理。

收到Vsync后处理Batch Move事件

下面从App收到Vsync信号调用CALLBACK_INPUT类型的回调ConsumeBatchedInputRunnable开始分析。

    final class ConsumeBatchedInputRunnable implements Runnable {
        @Override
        public void run() {
            // 处理Batch事件
            doConsumeBatchedInput(mChoreographer.getFrameTimeNanos());
        }
    }

    void doConsumeBatchedInput(long frameTimeNanos) {
        if (mConsumeBatchedInputScheduled) {
            mConsumeBatchedInputScheduled = false;
            if (mInputEventReceiver != null) {
                // 调用WindowInputEventReceiver的consumeBatchedInputEvents处理事件
                if (mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos)
                        && frameTimeNanos != -1) {
                    // If we consumed a batch here, we want to go ahead and schedule the
                    // consumption of batched input events on the next frame. Otherwise, we would
                    // wait until we have more input events pending and might get starved by other
                    // things occurring in the process. If the frame time is -1, however, then
                    // we're in a non-batching mode, so there's no need to schedule this.
                    // 请求绘制下一帧时处理Batch事件
                    scheduleConsumeBatchedInput();
                }
            }
            // 处理事件
            doProcessInputEvents();
        }
    }

    public final boolean consumeBatchedInputEvents(long frameTimeNanos) {
        if (mReceiverPtr == 0) {
            Log.w(TAG, "Attempted to consume batched input events but the input event "
                    + "receiver has already been disposed.");
        } else {
            // mReceiverPtr为NativeInputEventReceiver的地址
            return nativeConsumeBatchedInputEvents(mReceiverPtr, frameTimeNanos);
        }
        return false;
    }

static jboolean nativeConsumeBatchedInputEvents(JNIEnv* env, jclass clazz, jlong receiverPtr,
        jlong frameTimeNanos) {
    sp receiver =
            reinterpret_cast(receiverPtr);
    bool consumedBatch;
    // 调用NativeInputEventReceiver的consumeEvents方法
    // 这里参数consumeBatches为true, frameTimeNanos不为-1
    status_t status = receiver->consumeEvents(env, true /*consumeBatches*/, frameTimeNanos,
            &consumedBatch);
    if (status && status != DEAD_OBJECT && !env->ExceptionCheck()) {
        String8 message;
        message.appendFormat("Failed to consume batched input event.  status=%d", status);
        jniThrowRuntimeException(env, message.string());
        return JNI_FALSE;
    }
    return consumedBatch ? JNI_TRUE : JNI_FALSE;
}

下面看consumeEvents()的处理

status_t NativeInputEventReceiver::consumeEvents(JNIEnv* env,
        bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) {
    // consumeBatches为true
    if (consumeBatches) {
        mBatchedInputEventPending = false;
    }
    // outConsumedBatch不为NULL
    if (outConsumedBatch) {
        *outConsumedBatch = false;
    }

    ScopedLocalRef receiverObj(env, NULL);
    bool skipCallbacks = false;
    for (;;) {
        uint32_t seq;
        InputEvent* inputEvent;
        // 读取Batch事件放入inputEvent中,这里status通常返回OK
        status_t status = mInputConsumer.consume(&mInputEventFactory,
                consumeBatches, frameTime, &seq, &inputEvent);
        ......
        if (!skipCallbacks) {
            if (!receiverObj.get()) {
                receiverObj.reset(jniGetReferent(env, mReceiverWeakGlobal));
                if (!receiverObj.get()) {
                    ALOGW("channel '%s' ~ Receiver object was finalized "
                            "without being disposed.", getInputChannelName());
                    return DEAD_OBJECT;
                }
            }

            jobject inputEventObj;
            switch (inputEvent->getType()) {
            ......
            case AINPUT_EVENT_TYPE_MOTION: {
                if (kDebugDispatchCycle) {
                    ALOGD("channel '%s' ~ Received motion event.", getInputChannelName());
                }
                MotionEvent* motionEvent = static_cast(inputEvent);
                // 处理Batch Move事件
                if ((motionEvent->getAction() & AMOTION_EVENT_ACTION_MOVE) && outConsumedBatch) {
                    *outConsumedBatch = true;
                }
                inputEventObj = android_view_MotionEvent_obtainAsCopy(env, motionEvent);
                break;
            }
            ......
            }

            if (inputEventObj) {
                if (kDebugDispatchCycle) {
                    ALOGD("channel '%s' ~ Dispatching input event.", getInputChannelName());
                }
                // 调用InputEventReceiver的dispatchInputEvent方法处理
                env->CallVoidMethod(receiverObj.get(),
                        gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj);
                if (env->ExceptionCheck()) {
                    ALOGE("Exception dispatching input event.");
                    skipCallbacks = true;
                }
                env->DeleteLocalRef(inputEventObj);
            } else {
                ALOGW("channel '%s' ~ Failed to obtain event object.", getInputChannelName());
                skipCallbacks = true;
            }
        }
        ......
    }
}

status_t InputConsumer::consume(InputEventFactoryInterface* factory,
        bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
    ......
    *outSeq = 0;
    *outEvent = NULL;

    // Fetch the next input message.
    // Loop until an event can be returned or no additional events are received.
    while (!*outEvent) {
        if (mMsgDeferred) {
            // mMsg contains a valid input message from the previous call to consume
            // that has not yet been processed.
            mMsgDeferred = false;
        } else {
            // Receive a fresh message.
            // 读取消息,这里通常返回WOULD_BLOCK
            status_t result = mChannel->receiveMessage(&mMsg); 
            if (result) {
                // Consume the next batched event unless batches are being held for later.
                // consumeBatches为true,处理Batch事件
                if (consumeBatches || result != WOULD_BLOCK) {
                    result = consumeBatch(factory, frameTime, outSeq, outEvent);
                    if (*outEvent) {
#if DEBUG_TRANSPORT_ACTIONS
                        ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
                                mChannel->getName().string(), *outSeq);
#endif                  
                        // 这里(*outEvent不为NULL),跳出while循环
                        break;
                    }
                }
                return result;
            }
        }
        ......
    }
    //返回
    return OK;
}

status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
        nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
    status_t result;
    for (size_t i = mBatches.size(); i > 0; ) {
        i--;
        Batch& batch = mBatches.editItemAt(i);
        ......
        nsecs_t sampleTime = frameTime;
        if (mResampleTouch) {
            sampleTime -= RESAMPLE_LATENCY;
        }
        // 找到事件早于sampleTime的事件
        ssize_t split = findSampleNoLaterThan(batch, sampleTime);
        if (split < 0) {
            continue;
        }
        // Batch中的事件合成一个MotionEvent
        result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
        const InputMessage* next;
        if (batch.samples.isEmpty()) {
            // Batch中无事件,移除Batch
            mBatches.removeAt(i);
            next = NULL;
        } else {
            // Batch中有晚于sampleTime的事件
            next = &batch.samples.itemAt(0);
        }
        if (!result && mResampleTouch) {
            // 重采样,采样事件信息存放到MotionEvent的mSamplexxx的最后
            // View层获取的Move事件的信息为采样事件信息
            // 针对next是否为NULL采样两种重采样算法,请参考http://www.masonchang.com/blog/2014/8/25/androids-touch-resampling-algorithm自行阅读resampleTouchState实现
            resampleTouchState(sampleTime, static_cast(*outEvent), next);
        }
        return result;
    }

无论直接处理还是Batch处理,最终都通过WindowInputEventReceiverdispatchInputEvent()处理,下面分析该过程。

事件从ViewRootImpl传递至Activity的过程

下面从WindowInputEventReceiverOnInputEvent()开始分析

    public void onInputEvent(InputEvent event) {
        // 调用enqueueInputEvent处理
        enqueueInputEvent(event, this, 0, true);
    }

    void enqueueInputEvent(InputEvent event,
            InputEventReceiver receiver, int flags, boolean processImmediately) {
        // receiver为WindowInputEventReceiver
        // flags为0, processImmediately为true
        adjustInputEventForCompatibility(event);
        // 事件封装成QueuedInputEvent
        QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);

        // Always enqueue the input event in order, regardless of its time stamp.
        // We do this because the application or the IME may inject key events
        // in response to touch events and we want to ensure that the injected keys
        // are processed in the order they were received and we cannot trust that
        // the time stamp of injected events are monotonic.
        QueuedInputEvent last = mPendingInputEventTail;
        // 事件插入待处理的事件队列
        if (last == null) {
            mPendingInputEventHead = q;
            mPendingInputEventTail = q;
        } else {
            last.mNext = q;
            mPendingInputEventTail = q;
        }
        mPendingInputEventCount += 1;
        // 更新systrace中,应用内"aq:pending:xxx"信息(增加计数)
        Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
                mPendingInputEventCount);

        if (processImmediately) {
            // 立即处理事件
            doProcessInputEvents();
        } else {
            scheduleProcessInputEvents();
        }
    }

    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;
            // 更新systrace中,应用内"aq:pending:xxx信息"(减少计数)
            Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
                    mPendingInputEventCount);

            // 对于Batch事件,eventTime为重采样事件时间,oldestEventTime为Batch的首个Move事件的时间
            long eventTime = q.mEvent.getEventTimeNano();
            long oldestEventTime = eventTime;
            if (q.mEvent instanceof MotionEvent) {
                MotionEvent me = (MotionEvent)q.mEvent;
                if (me.getHistorySize() > 0) {
                    oldestEventTime = me.getHistoricalEventTimeNano(0);
                }
            }
            mChoreographer.mFrameInfo.updateInputEventTime(eventTime, oldestEventTime);
            // 传递输入事件
            deliverInputEvent(q);
        }
        ......
    }

下面看deliverInputEvent()的实现

    private void deliverInputEvent(QueuedInputEvent q) {
        // systrace中,应用内"deliverInputEvent"的开始
        Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
                q.mEvent.getSequenceNumber());
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);
        }

        InputStage stage;
        // q.mFlags为0
        if (q.shouldSendToSynthesizer()) {
            stage = mSyntheticInputStage;
        } else {
            // 对于普通的MotionEvent shouldSkipIme返回true
            stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
        }

        if (stage != null) {
            // 传递给EarlyPostImeInputStage处理,多个InputStage采用职责链模式
            stage.deliver(q);
        } else {
            finishInputEvent(q);
        }
    }

下面看EarlyPostImeInputStage的对MotionEvent的处理

    public final void deliver(QueuedInputEvent q) {
        if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) {
            forward(q);
        } else if (shouldDropInputEvent(q)) {
            finish(q, false);
        } else {
            // 调用onProcess处理,然后调用apply
            apply(q, onProcess(q));
        }
    }

    protected int onProcess(QueuedInputEvent q) {
        if (q.mEvent instanceof KeyEvent) {
            return processKeyEvent(q);
        } else {
            final int source = q.mEvent.getSource();
            if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
                // 普通的MotionEvent为Pointer事件
                return processPointerEvent(q);
            }
        }
        return FORWARD;
    }

    private int processPointerEvent(QueuedInputEvent q) {
        final MotionEvent event = (MotionEvent)q.mEvent;
        // Translate the pointer event for compatibility, if needed.
        if (mTranslator != null) {
            mTranslator.translateEventInScreenToAppWindow(event);
        }
        // Enter touch mode on down or scroll.
        final int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
            // 确保窗口处于touch模式
            ensureTouchMode(true);
        }
        // Offset the scroll position.
        if (mCurScrollY != 0) {
            event.offsetLocation(0, mCurScrollY);
        }
        // Remember the touch position for possible drag-initiation.
        if (event.isTouchEvent()) {
            // 记录坐标,对与Batch事件是重采样坐标
            mLastTouchPoint.x = event.getRawX();
            mLastTouchPoint.y = event.getRawY();
            mLastTouchSource = event.getSource();
        }
        // 返回FORWARD
        return FORWARD;
    }

    protected void apply(QueuedInputEvent q, int result) {
        // 根据onProcess返回的结果,进行相应的处理
        if (result == FORWARD) {
            // forward中调用onDeliverToNext
            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);
        }
    }

    protected void onDeliverToNext(QueuedInputEvent q) {
        if (DEBUG_INPUT_STAGES) {
            Log.v(mTag, "Done with " + getClass().getSimpleName() + ". " + q);
        }
        这里mNext为NativePostImeInputStage
        if (mNext != null) {
            mNext.deliver(q);
        } else {
            finishInputEvent(q);
        }
    }

EarlyPostImeInputStage处理完事件后,传递给NativePostImeInputStage处理,NativePostImeInputStage的处理过程非常简单,下面直接看ViewPostImeInputStage的处理。

    protected int onProcess(QueuedInputEvent q) {
        if (q.mEvent instanceof KeyEvent) {
            return processKeyEvent(q);
        } else {
            final int source = q.mEvent.getSource();
            if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
                // 处理Pointer MotionEvent
                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;
        // 这里eventTarget为mView也就是DecorView
        final View eventTarget =
                (event.isFromSource(InputDevice.SOURCE_MOUSE) && mCapturingView != null) ?
                        mCapturingView : mView;
        mAttachInfo.mHandlingPointerEvent = true;
        // 调用DecorView的dispatchPointerEvent方法
        boolean handled = eventTarget.dispatchPointerEvent(event);
        maybeUpdatePointerIcon(event);
        mAttachInfo.mHandlingPointerEvent = false;
        if (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) {
            mUnbufferedInputDispatch = true;
            if (mConsumeBatchedInputScheduled) {
                scheduleConsumeBatchedInputImmediately();
            }
        }
        // handled为true,事件处理完成
        // handled为false,事件没有处理,继续传递给下一个InputStage,当InputStage为null时,事件处理完成
        return handled ? FINISH_HANDLED : FORWARD;
    }

    public final boolean dispatchPointerEvent(MotionEvent event) {
        if (event.isTouchEvent()) {
            // 调用dispatchTouchEvent继续处理
            return dispatchTouchEvent(event);
        } else {
            return dispatchGenericMotionEvent(event);
        }
    }

    public boolean dispatchTouchEvent(MotionEvent ev) {
        // 这里cb为Activity,Activity实现了Window.Callback
        final Window.Callback cb = mWindow.getCallback();
        return cb != null && !mWindow.isDestroyed() && mFeatureId < 0
                ? cb.dispatchTouchEvent(ev) : super.dispatchTouchEvent(ev);
    }

至此,Motion事件已经传递给Activity,下面看Motion事件在Activity窗口内传递的过程。

Motion事件在Activity窗口内传递的过程

下面从ActivitydispatchTouchEvent()开始分析

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 用户交互回调
            onUserInteraction();
        }
        // 调用PhoneWindow的superDispatchTouchEvent
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        // Activity内没有View处理(可处理窗口范围外的事件)
        return onTouchEvent(ev);
    }
  • 这里可以重写ActivitydispatchTouchEvent截获所有Touch事件

下面看PhoneWindowsuperDispatchTouchEvent()的实现

    public boolean superDispatchTouchEvent(MotionEvent event) {
        // 调用DecorView的superDispatchTouchEvent方法
        return mDecor.superDispatchTouchEvent(event);
    }

    public boolean superDispatchTouchEvent(MotionEvent event) {
        // DecorView继承自FrameLayout, FrameLayout继承自ViewGroup
        // 调用ViewGroup的dispatchTouchEvent方法
        return super.dispatchTouchEvent(event);
    }

下面分析ViewGroupdispatchTouchEvent()实现

    public boolean dispatchTouchEvent(MotionEvent ev) {
        // 用于调试目的
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }
        ......
        // 根据安全策略过滤事件
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // Handle an initial down.
            // Down事件,清理TouchState
            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.
                // 清理先前Touch事件的TouchStage,通常不需要(up事件时会清理),但在app switch、ANR等一些情况下
                // 之前的Touch事件的up/cancel事件可能被丢弃
                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) {
                    // 检查是否拦截,默认不拦截Motion事件,子类可重写
                    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.
                // 对于非Down事件,如果没有touch targets,拦截
                intercepted = true;
            }

            // Check for cancelation.
            // 检查是否需要取消
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;
            ......
            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;
                // 对于Down事件
                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;
                    ......
                    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.
                        // 从前到后查找子View,找到能够接收事件的孩子
                        final ArrayList 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);
                            ......
                            // View是否可以接收Pointer事件,事件坐标是否在View区域内
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                            newTouchTarget = getTouchTarget(child);
                            // 分发Down事件给子View
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                // Child wants to receive touch within its bounds.
                                // 子View处理了事件
                                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();
                                // 子View封装为TouchTarget,添加到TouchTarget链表中
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }
                            ......
                        }
                        ......
                    }
                }
            }

            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // 没有touch targets,ViewGroup像普通View一样分发
                // 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;
                // 遍历TouchTarget链表分发事件
                while (target != null) {
                    final TouchTarget next = target.next;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        // 已经分发给该TouchTarget,如Down事件
                        handled = true;
                    } else {
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        // 分发非Down事件给TouchTarget对应的子View
                        // 如果cancelChild为true,分发CANCEL事件
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
                        if (cancelChild) {
                            // cancelChild为true,删除当前的TouchTarget
                            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) {
                // 如果是CANCEL或者UP事件,重置TouchState
                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;
    }

这里简单总结下Touch事件的处理:

  • 处理Down事件时,确定TouchTarget树,此后MOVE/UP事件沿着TouchTarget树分发
  • 分发MOVE/UP事件时,如果中途被拦截,则向子树发送CANCEL事件,删除子View对应的TouchTarget
  • 处理UP/CANCEL事件时,会重置TouchTarget

对于后续的处理过程,这里暂不讨论,请自行撸码,欢迎讨论交流。

你可能感兴趣的:(Android应用处理MotionEvent的过程)