Android Framework-Input-4 IQ到OQ

329 阅读8分钟

开局叠甲,可能理解有误,请大佬们斧正。

loopOnce()方法最后调用了 mQueuedListener->flush();

我们在数据处理看到最后调用到了 InputDispatcher.notifyMotion(),继续往下看。

//native/services/inputflinger/dispatcher/InputDispatcher.cpp

void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
//省略
    if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
                             args->pointerProperties)) {
        return;
    }

    uint32_t policyFlags = args->policyFlags;
  //是否是受信任的 那种adb 命令下来的 是不受信任的
    policyFlags |= POLICY_FLAG_TRUSTED;

    android::base::Timer t;
  //是否要拦击 一般情况下触摸这种 不会进入 但是按键(电源键 音量)那类会 想直接去响应而不是等派发下去
  // 比如anr了 不能让关机都不好使吧
    mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
    if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
        ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
              std::to_string(t.duration().count()).c_str());
    }

    bool needWake;
    { // acquire lock
        mLock.lock();

        if (shouldSendMotionToInputFilterLocked(args)) {//是否进入过滤器 一般不进入
            mLock.unlock();

            MotionEvent event;
            ui::Transform transform;
            event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
                             args->action, args->actionButton, args->flags, args->edgeFlags,
                             args->metaState, args->buttonState, args->classification, transform,
                             args->xPrecision, args->yPrecision, args->xCursorPosition,
                             args->yCursorPosition, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
                             AMOTION_EVENT_INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
                             args->pointerCount, args->pointerProperties, args->pointerCoords);

            policyFlags |= POLICY_FLAG_FILTERED;
            if (!mPolicy->filterInputEvent(&event, policyFlags)) {
                return; // event was consumed by the filter
            }

            mLock.lock();
        }

        // 构建出来  MotionEntry
        std::unique_ptr<MotionEntry> newEntry =
                std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
                                              args->source, args->displayId, policyFlags,
                                              args->action, args->actionButton, args->flags,
                                              args->metaState, args->buttonState,
                                              args->classification, args->edgeFlags,
                                              args->xPrecision, args->yPrecision,
                                              args->xCursorPosition, args->yCursorPosition,
                                              args->downTime, args->pointerCount,
                                              args->pointerProperties, args->pointerCoords, 0, 0);

      //入队  
      needWake = enqueueInboundEventLocked(std::move(newEntry));
        mLock.unlock();
    } // release lock

    //如果true 就wake 唤醒 looper  这个looper 就是默认的looper mLooper->pollOnce 会将looper 等待 这里就直接唤醒了  触发 dispatchOnce 让looper 去触发 也就是会触发 dispatchOnce()
    //这个是在前面start里的方法
    if (needWake) {
        mLooper->wake();
    }
}


enqueueInboundEventLocked 开始进入IQ队列

bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
    bool needWake = mInboundQueue.empty();
    mInboundQueue.push_back(std::move(newEntry));//加入尾部
    EventEntry& entry = *(mInboundQueue.back());
    traceInboundQueueLengthLocked();
​
    switch (entry.type) {
        case EventEntry::Type::KEY: {
            // Optimize app switch latency.
          
            const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
            if (isAppSwitchKeyEvent(keyEntry)) {
                if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
                    mAppSwitchSawKeyDown = true;
                } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
                    if (mAppSwitchSawKeyDown) {
                      
               mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
                        mAppSwitchSawKeyDown = false;
                        needWake = true;
                    }
                }
            }
            break;
        }
​
        case EventEntry::Type::MOTION: {//暂时只关心这种类型
             //符合条件就返true 一些条件的判断 这里好像只是塞进去又拿出来了,其实是因为switch那 我们没管
            if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
                mNextUnblockedEvent = mInboundQueue.back();//取出最后一个,我理解为ANR时间的判断。
                //返回true
                needWake = true;
            }
            break;
        }
         //省略 
        }
    }
​
    return needWake;
}

mLooper->wake(); 会唤醒InputDispatcherdispatchOnce()

void InputDispatcher::dispatchOnce() {
    nsecs_t nextWakeupTime = LONG_LONG_MAX;
    { // acquire lock
        std::scoped_lock _l(mLock);
        mDispatcherIsAlive.notify_all();
​
        //判断是否有命令需要去执行 默认没有 该方法进行了取反所以会进入,这里面的代码其实是检查是否ANR的核心代码。
      
        if (!haveCommandsLocked()) {
            dispatchOnceInnerLocked(&nextWakeupTime);
        }
​
     
        if (runCommandsLockedInterruptible()) {
            nextWakeupTime = LONG_LONG_MIN;
        }
​
      
        const nsecs_t nextAnrCheck = processAnrsLocked();
        nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
​
     
        if (nextWakeupTime == LONG_LONG_MAX) {
            mDispatcherEnteredIdle.notify_all();
        }
    } // release lock
​
  
    nsecs_t currentTime = now();
    int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
    mLooper->pollOnce(timeoutMillis);//简单理解等待多长时间
}

dispatchOnceInnerLocked

//内部进行派发
void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
    nsecs_t currentTime = now();
​
 
   //一般不进去
    if (!mDispatchEnabled) {
        resetKeyRepeatLocked();
    }
​
    //是否冻结了屏幕 一般不为冻结
    if (mDispatchFrozen) {
        //省略
        return;
    }
​
​
    bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
    if (mAppSwitchDueTime < *nextWakeupTime) {
        *nextWakeupTime = mAppSwitchDueTime;
    }
​
// mPendingEvent 默认为null
    if (!mPendingEvent) {
      //队列不为null走else
        if (mInboundQueue.empty()) {
            if (isAppSwitchDue) {
               
                resetPendingAppSwitchLocked(false);
                isAppSwitchDue = false;
            }
​
            // Synthesize a key repeat if appropriate.
            if (mKeyRepeatState.lastKeyEntry) {
                if (currentTime >= mKeyRepeatState.nextRepeatTime) {
                    mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
                } else {
                    if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
                        *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
                    }
                }
            }
​
           
            if (!mPendingEvent) {
                return;
            }
        } else {
            //拿第一个消息
            mPendingEvent = mInboundQueue.front();
            mInboundQueue.pop_front();//移除第一个消息
            
            traceInboundQueueLengthLocked();
        }
​
        // 判断是否是发往user 一般是
        if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
          //发给对应的页面  让对应的页面别休眠  保持亮起 记录用户活动
            pokeUserActivityLocked(*mPendingEvent);
        }
    }
​
​
  
  //接下来就是事件的抛弃 我们一般不抛弃
    bool done = false;
    DropReason dropReason = DropReason::NOT_DROPPED;
    if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
        dropReason = DropReason::POLICY;
    } else if (!mDispatchEnabled) {
        dropReason = DropReason::DISABLED;
    }
​
    if (mNextUnblockedEvent == mPendingEvent) {
        mNextUnblockedEvent = nullptr;
    }
​
    switch (mPendingEvent->type) {
       //省略
       
​
       
​
​
        case EventEntry::Type::MOTION: {
            std::shared_ptr<MotionEntry> motionEntry =
                    std::static_pointer_cast<MotionEntry>(mPendingEvent);
            if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
                dropReason = DropReason::APP_SWITCH;
            }
            if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
                dropReason = DropReason::STALE;
            }
            if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
                dropReason = DropReason::BLOCKED;
            }
          //进入  dispatchMotionLocked 这里传递的是第一个事件 也就是头部那个
            done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
            break;
        }
​
   
    }
​
    if (done) {
        if (dropReason != DropReason::NOT_DROPPED) {
            dropInboundEventLocked(*mPendingEvent, dropReason);
        }
        mLastDropReason = dropReason;
​
        releasePendingEventLocked();
        *nextWakeupTime = LONG_LONG_MIN; 
    }
}

pokeUserActivityLocked触发当前触摸的屏幕,别黑屏/锁屏了,不然分发给谁。

void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
    if (eventEntry.type == EventEntry::Type::FOCUS ||
        eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
        eventEntry.type == EventEntry::Type::DRAG) {
       
        return;
    }
    int32_t displayId = getTargetDisplayId(eventEntry);
    sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
    if (focusedWindowHandle != nullptr) {
        const InputWindowInfo* info = focusedWindowHandle->getInfo();
        if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
           //省略
            return;
        }
    }
​
    int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
    switch (eventEntry.type) {
        case EventEntry::Type::MOTION: {
            const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
            if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
                return;
            }
​
            if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
              //主要考touch 去保持活动
                eventType = USER_ACTIVITY_EVENT_TOUCH;
            }
            break;
        }
        //省略
    }
//调用 doPokeUserActivityLockedInterruptible  发往native 页面
    std::unique_ptr<CommandEntry> commandEntry =
            std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
    commandEntry->eventTime = eventEntry.eventTime;
    commandEntry->userActivityEventType = eventType;
    commandEntry->displayId = displayId;
    postCommandLocked(std::move(commandEntry));
}

doPokeUserActivityLockedInterruptible

void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
    mLock.unlock();
  // mpolicy 其实是com_android_server_input_InputManagerService
    mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
                              commandEntry->displayId);
​
    mLock.lock();
}
​
​
//---->com_android_server_input_InputManagerService
//base/services/core/jni/com_android_server_input_InputManagerService.cpp
void NativeInputManager::pokeUserActivity(nsecs_t eventTime, int32_t eventType, int32_t displayId) {
    ATRACE_CALL();
   // 调用 com_android_server_power_PowerManagerService.cpp 里面的该方法 
    //然后回调 到  PowerManagerService.java 的  userActivityFromNative() 不追了太多了
    android_server_PowerManagerService_userActivity(eventTime, eventType, displayId);
}
​

dispatchMotionLocked

bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
                                           DropReason* dropReason, nsecs_t* nextWakeupTime) {
    ATRACE_CALL();
    // 是否在派发中 
    if (!entry->dispatchInProgress) {
        entry->dispatchInProgress = true;
        //日志
        logOutboundMotionDetails("dispatchMotion - ", *entry);
    }
​
   
    if (*dropReason != DropReason::NOT_DROPPED) {
        setInjectionResult(*entry,
                           *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
                                                             : InputEventInjectionResult::FAILED);
        return true;
    }
​
  //是否一般是点  一般是点
    bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
​
    // 目标 触摸的目标窗口
    std::vector<InputTarget> inputTargets;
​
    bool conflictingPointerActions = false;
    InputEventInjectionResult injectionResult;
  //触摸屏处理
    if (isPointerEvent) {
       
        injectionResult =
                findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
                                               &conflictingPointerActions);
    } else {
        //非触摸屏  
        //寻找目标窗口 比如activity 等
        injectionResult =
                findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
    }
    if (injectionResult == InputEventInjectionResult::PENDING) {
        return false;
    }
​
  //模拟注入
    setInjectionResult(*entry, injectionResult);
    if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
       
        return true;
    }
    if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
        CancelationOptions::Mode mode(isPointerEvent
                                              ? CancelationOptions::CANCEL_POINTER_EVENTS
                                              : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
        CancelationOptions options(mode, "input event injection failed");
        synthesizeCancelationEventsForMonitorsLocked(options);
        return true;
    }
​
     //找到窗口后 添加全局的监测   获取目标的display glob monitors 不管你什么应用我都能吃到
    addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
​
    if (isPointerEvent) {
        std::unordered_map<int32_t, TouchState>::iterator it =
                mTouchStatesByDisplay.find(entry->displayId);
        if (it != mTouchStatesByDisplay.end()) {
            const TouchState& state = it->second;
            if (!state.portalWindows.empty()) {
​
                for (size_t i = 0; i < state.portalWindows.size(); i++) {
                    const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
                    addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
                                                     -windowInfo->frameLeft, -windowInfo->frameTop);
                }
            }
        }
    }
​
   
    if (conflictingPointerActions) {
        CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
                                   "conflicting pointer actions");
        synthesizeCancelationEventsForAllConnectionsLocked(options);
    }
  //继续调用这
    dispatchEventLocked(currentTime, entry, inputTargets);
    return true;
}

findFocusedWindowTargetsLocked 寻找目标窗口(这个方法还挺重要的,如何找要命中的窗口)

InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
        nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
        nsecs_t* nextWakeupTime) {
    std::string reason;
​
    int32_t displayId = getTargetDisplayId(entry);
    sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
    std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
            getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
​
    
    if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
        
        return InputEventInjectionResult::FAILED;
    }
​
    if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
        if (!mNoFocusedWindowTimeoutTime.has_value()) {
            
            std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
                    DEFAULT_INPUT_DISPATCHING_TIMEOUT);
            mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
            mAwaitedFocusedApplication = focusedApplicationHandle;
            mAwaitedApplicationDisplayId = displayId;
            
            *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
            return InputEventInjectionResult::PENDING;
        } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
            // Already raised ANR. Drop the event
           
            return InputEventInjectionResult::FAILED;
        } else {
            // Still waiting for the focused window
            return InputEventInjectionResult::PENDING;
        }
    }
​
    // we have a valid, non-null focused window
    resetNoFocusedWindowTimeoutLocked();
​
    // Check permissions.
    if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
        return InputEventInjectionResult::PERMISSION_DENIED;
    }
​
    if (focusedWindowHandle->getInfo()->paused) {
        
        return InputEventInjectionResult::PENDING;
    }
​
    
    if (entry.type == EventEntry::Type::KEY) {
        if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
            *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
            return InputEventInjectionResult::PENDING;
        }
    }
​
    // Success!  Output targets.
    addWindowTargetLocked(focusedWindowHandle,
                          InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
                          BitSet32(0), inputTargets);
​
    // Done.
    return InputEventInjectionResult::SUCCEEDED;
}

dispatchEventLocked 事件的分发

void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
                                          std::shared_ptr<EventEntry> eventEntry,
                                          const std::vector<InputTarget>& inputTargets) {
    ATRACE_CALL();
​
​
    updateInteractionTokensLocked(*eventEntry, inputTargets);
​
    ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
   //保持屏幕活动状态
    pokeUserActivityLocked(*eventEntry);
​
    //找到了对应的触摸屏幕 也加了全局的触摸
    for (const InputTarget& inputTarget : inputTargets) {
        sp<Connection> connection =
                getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
        if (connection != nullptr) {
          //调用这里
            prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
        } 
    }
}

prepareDispatchCycleLocked 事件的分离

void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
                                                 const sp<Connection>& connection,
                                                 std::shared_ptr<EventEntry> eventEntry,
                                                 const InputTarget& inputTarget) {
​
//省略
​
   
    if (connection->status != Connection::STATUS_NORMAL) {
    if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
       //分离事件
       
        const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
        if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
            std::unique_ptr<MotionEntry> splitMotionEntry =
                    splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
            if (!splitMotionEntry) {
                return; // split event was dropped
            }
           //省略
            enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
                                         inputTarget);
            return;
        }
    }
​
 
     //走这里
    enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
}

enqueueDispatchEntriesLocked 入队

void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
                                                   const sp<Connection>& connection,
                                                   std::shared_ptr<EventEntry> eventEntry,
                                                   const InputTarget& inputTarget) {
//省略
​
    bool wasEmpty = connection->outboundQueue.empty();
​
    // Enqueue dispatch entries for the requested modes.
    enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
                               InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
    enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
                               InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
    enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
                               InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
  //正常是这种 上面传递了 findFocusedWindowTargetsLocked 里面添加的
    enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
                               InputTarget::FLAG_DISPATCH_AS_IS);
    enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
                               InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
    enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
                               InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
​
    // If the outbound queue was previously empty, start the dispatch cycle going.
    if (wasEmpty && !connection->outboundQueue.empty()) {
      //开始派发数据
        startDispatchCycleLocked(currentTime, connection);
    }
}

enqueueDispatchEntryLocked 将过滤拼凑好的数据,塞入要对外分发的队列

void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
                                                 std::shared_ptr<EventEntry> eventEntry,
                                                 const InputTarget& inputTarget,
                                                 int32_t dispatchMode) {
 
    int32_t inputTargetFlags = inputTarget.flags;
    if (!(inputTargetFlags & dispatchMode)) {
        return;
    }
    inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
​
   
    std::unique_ptr<DispatchEntry> dispatchEntry =
            createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
    EventEntry& newEntry = *(dispatchEntry->eventEntry);
    
    switch (newEntry.type) {
         //我们正常是MOTION
​
        case EventEntry::Type::MOTION: {
            const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
​
            constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
                    static_cast<int32_t>(IdGenerator::Source::OTHER);
            dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
            if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
                dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
            } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
                dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
            } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
                dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
            } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
                dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
            } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
                dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
            } else {
              //我们是 FLAG_DISPATCH_AS_IS 走else
                dispatchEntry->resolvedAction = motionEntry.action;
                dispatchEntry->resolvedEventId = motionEntry.id;
            }
          //如果是move 鼠标相关
            if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
                !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
                                                   motionEntry.displayId)) {
​
​
                dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
            }
​
            dispatchEntry->resolvedFlags = motionEntry.flags;
            if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
                dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
            }
            if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
                dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
            }
​
             //trackMotion 主要处理 异常的事件 比如没有down 就来了move
            if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
                                                    dispatchEntry->resolvedFlags)) {
​
                return; // skip the inconsistent event
            }
​
            dispatchEntry->resolvedEventId =
                    dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
                    ? mIdGenerator.nextId()
                    : motionEntry.id;
           
​
            if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
                (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
             
                break;
            }
​
            dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
                                            inputTarget.inputChannel->getConnectionToken());
​
            break;
        }
      
    }
​
   
    if (dispatchEntry->hasForegroundTarget()) {
        incrementPendingForegroundDispatches(newEntry);
    }
​
    // 把要分发的事件放进去,mInboundQueue是 Reader 往Dispatcher 塞的队列,
    //outboundQueue是弄好了要分发出去的 这里的connection 简单理解就是目标window
    connection->outboundQueue.push_back(dispatchEntry.release());
    traceOutboundQueueLength(*connection);
}

总结一下: 当一个新鲜的事件读到以后,会塞入到IQ的尾巴里,然后进行事件类型的判断,返回是否唤醒,一般是唤醒, mLooper->wake(); 会唤醒InputDispatcherdispatchOnce(),拿出第一个事件,这里我们先不考ANR问题,并删除IQ中的第一个,在此期间保证屏幕的亮屏,寻找对应的屏幕窗口,找到命中的window,进行在此数据的封装改造,找到对应windowconnection,塞入到 OQ的最后面。