在 AOSP 15 中,InputManager 的源码体系是一个高度解耦的生产者-消费者模型。它横跨了 Java 层(业务逻辑)、Native 层(核心引擎)和内核层(硬件驱动)。
一、 架构总览:三层模型
在 AOSP 15 中,输入系统的流转路径如下: Linux Kernel (驱动生成) <math xmlns="http://www.w3.org/1998/Math/MathML"> → \rightarrow </math>→ InputReader (加工) <math xmlns="http://www.w3.org/1998/Math/MathML"> → \rightarrow </math>→ InputDispatcher (分发) <math xmlns="http://www.w3.org/1998/Math/MathML"> → \rightarrow </math>→ App Window (消耗)。

二、初始化与创建流程 (Creation)
InputManager 的诞生始于系统启动阶段,经历了从 Java 到 Native 的握手。
Step 1: Java 层实例化
在 SystemServer.java 的 startOtherServices 方法中:
-
动作:new InputManagerService(context)。
-
作用:作为 Binder 服务注册到 ServiceManager,供应用层访问权限、焦点等信息。
java
private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
....
t.traceBegin("StartInputManagerService");
if (inputManagerLifecycleSupport()) {
inputManager = mSystemServiceManager.startService(
InputManagerService.Lifecycle.class).getService();
} else {
// 创建InputManagerService
inputManager = new InputManagerService(context);
}
t.traceEnd();
....
t.traceBegin("StartWindowManagerService");
//等待sensor传感器服务启动完成
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_SENSOR_SERVICE);
wm = WindowManagerService.main(context, inputManager, !mFirstBoot,
new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_HIGH
| DUMP_FLAG_PROTO);
if (!inputManagerLifecycleSupport()) {
ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
}
t.traceEnd();
t.traceBegin("SetWindowManagerService");
mActivityManagerService.setWindowManager(wm);
t.traceEnd();
t.traceBegin("WindowManagerServiceOnInitReady");
wm.onInitReady();
t.traceEnd();
....
t.traceBegin("StartInputManager");
inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback());
// 启动线程
inputManager.start();
t.traceEnd();
}
Step 2: Native 层核心构建 (关键)
Java 层的构造函数触发 JNI 调用 nativeInit,进入 com_android_server_input_InputManagerService.cpp:
- 实例化 NativeInputManager:它是 Java IMS 在 Native 层的代表。
Native层面的InputManager启动
源码路径:frameworks/base/services/core/java/com/android/server/input/InputManagerService.java
java
InputManagerService(Injector injector) {
...
mContext = injector.getContext();
mHandler = new InputManagerHandler(injector.getLooper());
mNative = injector.getNativeService(this);
...
}
Injector实现,InputManagerService里面的静态内部类
源码路径:frameworks/base/services/core/java/com/android/server/input/InputManagerService.Injector.java
c++
NativeInputManagerService getNativeService(InputManagerService service) {
return new NativeInputManagerService.NativeImpl(service, mLooper.getQueue());
}
InputManagerService的jni中nativeInit
源码路径:frameworks/base/services/core/jni/com_android_server_input_InputManagerService.cpp
c++
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);
}
-
创建 InputManager (Native对象):在 InputManager.cpp 构造函数中:
-
mDispatcher = createInputDispatcher(...):实例化分发器。
-
mReader = createInputReader(..., mDispatcher):实例化读取器,并将 Dispatcher 作为监听器传入。
-
c++
InputManager::InputManager(const sp<InputReaderPolicyInterface>& readerPolicy,
InputDispatcherPolicyInterface& dispatcherPolicy,
PointerChoreographerPolicyInterface& choreographerPolicy,
InputFilterPolicyInterface& inputFilterPolicy) {
mInputFlingerRust = createInputFlingerRust();
// 创建InputDispatcher
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));
// 创建InputReader
mReader = createInputReader(readerPolicy, *mTracingStages.back());
}
- 创建 EventHub:打开 /dev/input 目录,利用 inotify 和 epoll 准备监听硬件节点。
c++
EventHub::EventHub(void)
: mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
mNextDeviceId(1),
mControllerNumbers(),
mNeedToReopenDevices(false),
mNeedToScanDevices(true),
mPendingEventCount(0),
mPendingEventIndex(0),
mPendingINotify(false) {
ensureProcessCanBlockSuspend();
mEpollFd = epoll_create1(EPOLL_CLOEXEC);
LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
mINotifyFd = inotify_init1(IN_CLOEXEC);
LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
//省略部分
struct epoll_event eventItem = {};
eventItem.events = EPOLLIN | EPOLLWAKEUP;
eventItem.data.fd = mINotifyFd;
int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
int wakeFds[2];
result = pipe2(wakeFds, O_CLOEXEC);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
mWakeReadPipeFd = wakeFds[0];
mWakeWritePipeFd = wakeFds[1];
result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
errno);
result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
errno);
eventItem.data.fd = mWakeReadPipeFd;
result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
errno);
}
三. 启动流程 (Starting)
实例化完成后,系统通过 inputManager.start() 唤醒物理线程。
在 InputManager::start() 中,通过 InputThread::create 调用底层 pthread_create 生成两个核心 Linux 线程:
-
InputReaderThread:赋予 SCHED_FIFO 实时调度优先级。
-
InputDispatcherThread:同样具备高优先级,负责逻辑决策
这边只做一件事,就是启动线程
源码路径:native/services/inputflinger/InputManager.cpp
c++
status_t InputManager::start() {
status_t result = mDispatcher->start();
if (result) {
ALOGE("Could not start InputDispatcher thread due to error %d.", result);
return result;
}
result = mReader->start();
if (result) {
ALOGE("Could not start InputReader due to error %d.", result);
mDispatcher->stop();
return result;
}
return OK;
}
InputReader启动的时候会判断是否已经启动
源码路径:native/services/inputflinger/reader/InputReader.cpp
c++
status_t InputReader::start() {
if (mThread) {
return ALREADY_EXISTS;
}
// 旧版本是InputManager::initialize() 方法去创建,然后在mReaderThread->run,
// 新版本是直接start在判断是否已经创建启动
mThread = std::make_unique<InputThread>(
"InputReader", [this]() { loopOnce(); }, [this]() { mEventHub->wake(); },
/*isInCriticalPath=*/true);
return OK;
}
InputDispatcher启动的时候会判断是否已经启动
源码路径:native/services/inputflinger/dispatcher/InputDispatcher.cpp
c++
status_t InputDispatcher::start() {
if (mThread) {
return ALREADY_EXISTS;
}
// 旧版本是InputManager::initialize() mDispatcherThread->run,
// 新版本是直接start在判断是否已经创建启动
mThread = std::make_unique<InputThread>(
"InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); },
/*isInCriticalPath=*/true);
return OK;
}
总结
- 硬件层:用户手指触摸屏幕。
- Reader 线程:EventHub 唤醒 <math xmlns="http://www.w3.org/1998/Math/MathML"> → \rightarrow </math>→ TouchMapper 换算坐标 <math xmlns="http://www.w3.org/1998/Math/MathML"> → \rightarrow </math>→ 存入队列。
- Dispatcher 线程:从队列取件 <math xmlns="http://www.w3.org/1998/Math/MathML"> → \rightarrow </math>→ 命中测试找到目标窗口 <math xmlns="http://www.w3.org/1998/Math/MathML"> → \rightarrow </math>→ 通过 Socket 发送。
- App 进程:Looper 收到 Socket 信号 <math xmlns="http://www.w3.org/1998/Math/MathML"> → \rightarrow </math>→ 调用 View.onTouchEvent()。