InputReader与InputDispatcher关系 - android-15.0.0_r23

InputReader与InputDispatcher关系 - android-15.0.0_r23

InputManagerService启动-Android12


1、InputManager中创建

  • JNIcom_android_server_input_InputManagerService.cpp)连接 InputManagerService.javaInputManager.cpp
  • InputManager.cpp中去创建InputReaderInputDispatcher,都会持有 JNINativeInputManager
  • JNINativeInputManager 继承 InputReaderPolicyInterfaceInputDispatcherPolicyInterfacePointerControllerPolicyInterfacePointerChoreographerPolicyInterfaceInputFilterPolicyInterface

frameworks/base/services/core/java/com/android/server/input/InputManagerService.java

frameworks/base/services/core/java/com/android/server/input/NativeInputManagerService.java

java 复制代码
NativeImpl(InputManagerService service, MessageQueue messageQueue) {
    mPtr = init(service, messageQueue);
}

frameworks/base/services/core/jni/com_android_server_input_InputManagerService.cpp

cpp 复制代码
static jlong nativeInit(JNIEnv* env, jclass /* clazz */, jobject serviceObj,
                        jobject messageQueueObj) {
    sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueObj);
    if (messageQueue == nullptr) {
        jniThrowRuntimeException(env, "MessageQueue is not initialized.");
        return 0;
    }

    static std::once_flag nativeInitialize;
    NativeInputManager* im = nullptr;
    std::call_once(nativeInitialize, [&]() {
        // Create the NativeInputManager, which should not be destroyed or deallocated for the
        // lifetime of the process.
        im = new NativeInputManager(serviceObj, messageQueue->getLooper());
    });
    LOG_ALWAYS_FATAL_IF(im == nullptr, "NativeInputManager was already initialized.");
    return reinterpret_cast<jlong>(im);
}

NativeInputManager::NativeInputManager(jobject serviceObj, const sp<Looper>& looper)
      : mLooper(looper) {
    JNIEnv* env = jniEnv();

    mServiceObj = env->NewGlobalRef(serviceObj);

    InputManager* im = new InputManager(this, *this, *this, *this);
    mInputManager = im;
    defaultServiceManager()->addService(String16("inputflinger"), im);
}

frameworks/native/services/inputflinger/InputManager.cpp

cpp 复制代码
/**
 * The event flow is via the "InputListener" interface, as follows:
 *   InputReader
 *     -> UnwantedInteractionBlocker
 *     -> InputFilter
 *     -> PointerChoreographer
 *     -> InputProcessor
 *     -> InputDeviceMetricsCollector
 *     -> InputDispatcher
 */
InputManager::InputManager(const sp<InputReaderPolicyInterface>& readerPolicy,
                           InputDispatcherPolicyInterface& dispatcherPolicy,
                           PointerChoreographerPolicyInterface& choreographerPolicy,
                           InputFilterPolicyInterface& inputFilterPolicy) {
    mInputFlingerRust = createInputFlingerRust();

    mDispatcher = createInputDispatcher(dispatcherPolicy);
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("InputDispatcher", *mDispatcher));

    if (ENABLE_INPUT_FILTER_RUST) {
        mInputFilter = std::make_unique<InputFilter>(*mTracingStages.back(), *mInputFlingerRust,
                                                     inputFilterPolicy);
        mTracingStages.emplace_back(
                std::make_unique<TracedInputListener>("InputFilter", *mInputFilter));
    }

    if (ENABLE_INPUT_DEVICE_USAGE_METRICS) {
        mCollector = std::make_unique<InputDeviceMetricsCollector>(*mTracingStages.back());
        mTracingStages.emplace_back(
                std::make_unique<TracedInputListener>("MetricsCollector", *mCollector));
    }

    mProcessor = std::make_unique<InputProcessor>(*mTracingStages.back());
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("InputProcessor", *mProcessor));

    mChoreographer =
            std::make_unique<PointerChoreographer>(*mTracingStages.back(), choreographerPolicy);
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("PointerChoreographer", *mChoreographer));

    mBlocker = std::make_unique<UnwantedInteractionBlocker>(*mTracingStages.back());
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("UnwantedInteractionBlocker", *mBlocker));

    mReader = createInputReader(readerPolicy, *mTracingStages.back());
}

2、InputDispatcher

  • mPolicy(policy) 持有 JNINativeInputManager与上层IMS沟通桥梁
  • mTraceruser版本上Perfetto日志
  • mLooper = sp<Looper>::make(false) 控制线程休眠/激活;上层mNative.start()启动InputDispatcher的线程执行 dispatchOnce() ,并激活mLooper->wake()

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

cpp 复制代码
InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
      : InputDispatcher(policy, createInputTracingBackendIfEnabled()) {}

InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
                                 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
      : mPolicy(policy),
        mPendingEvent(nullptr),
        mLastDropReason(DropReason::NOT_DROPPED),
        mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
        mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
        mNextUnblockedEvent(nullptr),
        mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
        mDispatchEnabled(false),
        mDispatchFrozen(false),
        mInputFilterEnabled(false),
        mMaximumObscuringOpacityForTouch(1.0f),
        mFocusedDisplayId(ui::LogicalDisplayId::DEFAULT),
        mWindowTokenWithPointerCapture(nullptr),
        mAwaitedApplicationDisplayId(ui::LogicalDisplayId::INVALID),
        mInputEventTimelineProcessor(
                input_flags::enable_per_device_input_latency_metrics()
                        ? std::move(std::unique_ptr<InputEventTimelineProcessor>(
                                  new LatencyAggregatorWithHistograms()))
                        : std::move(std::unique_ptr<InputEventTimelineProcessor>(
                                  new LatencyAggregator()))),
        mLatencyTracker(*mInputEventTimelineProcessor) {
    mLooper = sp<Looper>::make(false);
    mReporter = createInputReporter();

    mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
#if defined(__ANDROID__)
    SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
#endif
    mKeyRepeatState.lastKeyEntry = nullptr;

    if (traceBackend) {
        mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
    }

    mLastUserActivityTimes.fill(0);
}

status_t InputDispatcher::start() {
    if (mThread) {
        return ALREADY_EXISTS;
    }
    mThread = std::make_unique<InputThread>(
            "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); },
            /*isInCriticalPath=*/true);
    return OK;
}

3、InputReader

  • mPolicy(policy) 持有 JNINativeInputManager与上层IMS沟通桥梁
  • mEventHub(eventHub) 获取底层input事件;控制start()启动的线程的休眠/激活
  • mNextListener(listener) 连接InputDispatcher,并新增了 mTracingStages 链表处理

frameworks/native/services/inputflinger/reader/InputReader.cpp

cpp 复制代码
InputReader::InputReader(std::shared_ptr<EventHubInterface> eventHub,
                         const sp<InputReaderPolicyInterface>& policy,
                         InputListenerInterface& listener)
      : mContext(this),
        mEventHub(eventHub),
        mPolicy(policy),
        mNextListener(listener),
        mKeyboardClassifier(std::make_unique<KeyboardClassifier>()),
        mGlobalMetaState(AMETA_NONE),
        mLedMetaState(AMETA_NONE),
        mGeneration(1),
        mNextInputDeviceId(END_RESERVED_ID),
        mDisableVirtualKeysTimeout(LLONG_MIN),
        mNextTimeout(LLONG_MAX),
        mConfigurationChangesToRefresh(0) {
    refreshConfigurationLocked(/*changes=*/{});
    updateGlobalMetaStateLocked();
}

status_t InputReader::start() {
    if (mThread) {
        return ALREADY_EXISTS;
    }
    mThread = std::make_unique<InputThread>(
            "InputReader", [this]() { loopOnce(); }, [this]() { mEventHub->wake(); },
            /*isInCriticalPath=*/true);
    return OK;
}

4、mTracingStages 链表

代码注释:The event flow is via the "InputListener" interface, as follows: InputReader -> UnwantedInteractionBlocker -> InputFilter -> PointerChoreographer -> InputProcessor -> InputDeviceMetricsCollector -> InputDispatcher

  • InputReadermNextListener(listener)持有链表head UnwantedInteractionBlocker
  • 当获取到事件后 mNextListener.notify(args) 执行链表mTracingStages

实际链表:
UnwantedInteractionBlocker PointerChoreographer InputProcessor InputDeviceMetricsCollector InputFilter InputDispatcher

frameworks/native/services/inputflinger/InputManager.cpp

cpp 复制代码
/**
 * The event flow is via the "InputListener" interface, as follows:
 *   InputReader
 *     -> UnwantedInteractionBlocker
 *     -> InputFilter
 *     -> PointerChoreographer
 *     -> InputProcessor
 *     -> InputDeviceMetricsCollector
 *     -> InputDispatcher
 */
InputManager::InputManager(const sp<InputReaderPolicyInterface>& readerPolicy,
                           InputDispatcherPolicyInterface& dispatcherPolicy,
                           PointerChoreographerPolicyInterface& choreographerPolicy,
                           InputFilterPolicyInterface& inputFilterPolicy) {
    mInputFlingerRust = createInputFlingerRust();

    mDispatcher = createInputDispatcher(dispatcherPolicy);
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("InputDispatcher", *mDispatcher));

    if (ENABLE_INPUT_FILTER_RUST) {
        mInputFilter = std::make_unique<InputFilter>(*mTracingStages.back(), *mInputFlingerRust,
                                                     inputFilterPolicy);
        mTracingStages.emplace_back(
                std::make_unique<TracedInputListener>("InputFilter", *mInputFilter));
    }

    if (ENABLE_INPUT_DEVICE_USAGE_METRICS) {
        mCollector = std::make_unique<InputDeviceMetricsCollector>(*mTracingStages.back());
        mTracingStages.emplace_back(
                std::make_unique<TracedInputListener>("MetricsCollector", *mCollector));
    }

    mProcessor = std::make_unique<InputProcessor>(*mTracingStages.back());
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("InputProcessor", *mProcessor));

    mChoreographer =
            std::make_unique<PointerChoreographer>(*mTracingStages.back(), choreographerPolicy);
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("PointerChoreographer", *mChoreographer));

    mBlocker = std::make_unique<UnwantedInteractionBlocker>(*mTracingStages.back());
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("UnwantedInteractionBlocker", *mBlocker));

    mReader = createInputReader(readerPolicy, *mTracingStages.back());
}

4.1 链表执行

  • 根据 NotifyArgs 事件类型调用对应方法。这里使用 std::visit 配合 lambda 访问者(Visitor) 来处理 std::variant 类型的事件分发。实质就是检查generalArgs 参数类型调用对应方法。
  • 按照任务链表mTracingStages依次执行。

frameworks/native/services/inputflinger/include/InputListener.h

frameworks/native/services/inputflinger/InputListener.cpp

cpp 复制代码
// Helper to std::visit with lambdas.
template <typename... V>
struct Visitor : V... { using V::operator()...; };
// explicit deduction guide (not needed as of C++20)
template <typename... V>
Visitor(V...) -> Visitor<V...>;

void InputListenerInterface::notify(const NotifyArgs& generalArgs) {
    Visitor v{
            [&](const NotifyInputDevicesChangedArgs& args) { notifyInputDevicesChanged(args); },
            [&](const NotifyKeyArgs& args) { notifyKey(args); },
            [&](const NotifyMotionArgs& args) { notifyMotion(args); },
            [&](const NotifySwitchArgs& args) { notifySwitch(args); },
            [&](const NotifySensorArgs& args) { notifySensor(args); },
            [&](const NotifyVibratorStateArgs& args) { notifyVibratorState(args); },
            [&](const NotifyDeviceResetArgs& args) { notifyDeviceReset(args); },
            [&](const NotifyPointerCaptureChangedArgs& args) { notifyPointerCaptureChanged(args); },
    };
    std::visit(v, generalArgs);
}

4.2 不同InputListenerInterface功能

InputListenerInterface 功能
UnwantedInteractionBlocker UnwantedInteractionBlocker接口的实现。表示输入处理的一个单独阶段。所有输入事件都经过这个阶段。充当除运动事件之外的所有输入事件的直通。运动类型的事件被发送到PalmRejectorsPalmRejector检测不需要的触摸,并在删除错误指针的情况下发出输入流。
PointerChoreographer PointerChrographer管理系统显示的用于输入交互的图标。这包括显示鼠标光标、手写笔悬停图标和触摸点。它负责累积鼠标光标的位置,并在必要时为传入事件填充光标位置。
InputProcessor InputProcessor接口的实现。表示输入处理的一个单独阶段。所有输入事件都经过这个阶段。充当除运动事件之外的所有输入事件的直通。运动类型的事件被发送到MotionClassifier。
InputDeviceMetricsCollector 为测试而注入的度量收集器的日志接口。ENABLE_INPUT_DEVICE_USAGE_METRICS开关控制
InputFilter InputFilterC++组件被设计为rust实现的包装器。ENABLE_INPUT_FILTER_RUST开关控制
InputDispatcher InputEvent 分发给目标窗口
相关推荐
领创工作室2 小时前
安卓设备分区作用详解-测试机红米K40
android·java·linux
hello_ludy2 小时前
Android 中的 mk 和 bp 文件编译说明
android·编译
maki0775 小时前
VR大空间资料 03 —— VRGK使用体验和源码分析
android·vr·虚幻·源码分析·oculus·htc vive·vrgk
white-persist6 小时前
【burp手机真机抓包】Burp Suite 在真机(Android and IOS)抓包手机APP + 微信小程序详细教程
android·前端·ios·智能手机·微信小程序·小程序·原型模式
安卓AndroidQ7 小时前
Android Studio 代码混淆核心解释
android·ide·android studio
qq_7391753697 小时前
Android Studio 实现四则运算+开方+倒数简易计算器
android·python·android studio
就叫飞六吧7 小时前
Android studio -kt构建一个app
android·ide·android studio
qluka9 小时前
Android 窗口结构(三) Home Task 添加Home ActivityRecord
android·开发语言
灿烂阳光g9 小时前
App进程是如何从Zygote中fork出来的
android