概述

当用户触摸屏幕或者按键操作,首次触发的是硬件驱动,驱动收到事件后,将该相应事件写入到输入设备节点, 这便产生了最原生态的内核事件。接着,输入系统取出原生态的事件,经过层层封装后成为KeyEvent或者MotionEvent ;最后,交付给相应的目标窗口(Window)来消费该输入事件。可见,输入系统在整个过程起到承上启下的衔接作用。

Input模块的主要组成:

  • Native层的InputReader负责从EventHub取出事件并处理,再交给InputDispatcher;
  • Native层的InputDispatcher接收来自InputReader的输入事件,并记录WMS的窗口信息,用于派发事件到合适的窗口;
  • Java层的InputManagerService跟WMS交互,WMS记录所有窗口信息,并同步更新到IMS,为InputDispatcher正确派发事件到ViewRootImpl提供保障;

InputManagerService启动

在SystemServer的main方法里面会调用startOtherServices。startOtherServices里面会启动InputManagerService。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
t.traceBegin("startOtherServices");
// 系统上下文对象
final Context context = mSystemContext;
// WindowManagerService,简称WMS
WindowManagerService wm = null;
SerialService serial = null;
NetworkTimeUpdateService networkTimeUpdater = null;
// InputManagerService, 简称IMS
InputManagerService inputManager = null;

//......
// 实例化InputManagerService
t.traceBegin("StartInputManagerService");
inputManager = new InputManagerService(context);
t.traceEnd();

// 启动WindowManagerService
t.traceBegin("StartWindowManagerService");
// WMS needs sensor service ready
ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);
mSensorServiceStart = null;
// InputManagerService和WindowManagerService进行绑定起来
wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
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();

// Start receiving calls from HIDL services. Start in in a separate thread
// because it need to connect to SensorManager. This have to start
// after START_SENSOR_SERVICE is done.
SystemServerInitThreadPool.submit(() -> {
TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
traceLog.traceBegin(START_HIDL_SERVICES);
startHidlServices();
traceLog.traceEnd();
}, START_HIDL_SERVICES);

if (!isWatch && enableVrService) {
t.traceBegin("StartVrManagerService");
mSystemServiceManager.startService(VrManagerService.class);
t.traceEnd();
}

t.traceBegin("StartInputManager");
// 给inputManager增加WindowManager的监听回调
inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback());
// 启动IputManager
inputManager.start();
t.traceEnd();
//.....
}

InputManagerService#start

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* 代码位于:framework/base/service/core/java/com/android/server/input/InputManagerService.java
*/
public InputManagerService(Context context) {
this.mContext = context;
// 初始化拿到显示线程的Handler。运行在线程"android.display"
this.mHandler = new InputManagerHandler(DisplayThread.get().getLooper());

mStaticAssociations = loadStaticInputPortAssociations();
mUseDevInputEventForAudioJack =
context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
+ mUseDevInputEventForAudioJack);
// 调用Native层的Init. 就是Native层对应的的对应的指针地址.
// 这个long型的独享是Native层的InputManager的指针地址。传入的参数是InputManagerService的上下文对象
// 获取HandlerThread的looper的MessageQueue
mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());

String doubleTouchGestureEnablePath = context.getResources().getString(
R.string.config_doubleTouchGestureEnableFile);
mDoubleTouchGestureEnableFile = TextUtils.isEmpty(doubleTouchGestureEnablePath) ? null :
new File(doubleTouchGestureEnablePath);
// 添加到LocalService的中
LocalServices.addService(InputManagerInternal.class, new LocalService());
}

public void start() {
Slog.i(TAG, "Starting input manager");
// 进行Native层的start。
nativeStart(mPtr);

// Add ourself to the Watchdog monitors.
// 进行WatchDog的监听
Watchdog.getInstance().addMonitor(this);

registerPointerSpeedSettingObserver();
registerShowTouchesSettingObserver();
registerAccessibilityLargePointerSettingObserver();
registerLongPressTimeoutObserver();

mContext.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updatePointerSpeedFromSettings();
updateShowTouchesFromSettings();
updateAccessibilityLargePointerFromSettings();
updateDeepPressStatusFromSettings("user switched");
}
}, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);

updatePointerSpeedFromSettings();
updateShowTouchesFromSettings();
updateAccessibilityLargePointerFromSettings();
updateDeepPressStatusFromSettings("just booted");
}

调用Native层的Init的初始化方法.上层传下来的MessageQueue。再进行强制类型转换会Native层的MessageQueue.同时实例化Native层的NativeInputManager对象。返回给上层。而在三

com_android_server_inputManagerService#nativeInit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// ----------------------------------------------------------------------------
/**
* 代码位于:framework/base/service/core/jni/com_android_server_inputManagerService.cpp
* 上层的framework/base/service/core/java/com/android/server/input/InputManagerService.java的实例化的时候回调用
**/
static jlong nativeInit(JNIEnv* env, jclass /* clazz */,
jobject serviceObj, jobject contextObj, jobject messageQueueObj) {
// 获取MessageQueue。上层传下来的MessageQueue。再进行强制类型转换会Native层的MessageQueue
sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueObj);
if (messageQueue == nullptr) {
jniThrowRuntimeException(env, "MessageQueue is not initialized.");
return 0;
}
// 初始化
NativeInputManager* im = new NativeInputManager(contextObj, serviceObj,
messageQueue->getLooper());
im->incStrong(0);
// 进行危险的强制类型转换
return reinterpret_cast<jlong>(im);
}

NativeInputManager::NativeInputManager(jobject contextObj,
jobject serviceObj, const sp<Looper>& looper) :
mLooper(looper), mInteractive(true) {
JNIEnv* env = jniEnv();
// 持有上层的InputManagerService的对象
mServiceObj = env->NewGlobalRef(serviceObj);

{
// 加上同步并发锁的实现
AutoMutex _l(mLock);
mLocked.systemUiVisibility = ASYSTEM_UI_VISIBILITY_STATUS_BAR_VISIBLE;
mLocked.pointerSpeed = 0;
mLocked.pointerGesturesEnabled = true;
mLocked.showTouches = false;
mLocked.pointerCapture = false;
mLocked.pointerDisplayId = ADISPLAY_ID_DEFAULT;
}
mInteractive = true;
// 实例化Native层的InputManager
mInputManager = new InputManager(this, this);
// 往ServiceManager进行注册inputflinger名称的InputManagerService
defaultServiceManager()->addService(String16("inputflinger"),
mInputManager, false);
}


/**
* InputManager的构造函数
**/
InputManager::InputManager(
const sp<InputReaderPolicyInterface>& readerPolicy,
const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {
// 创建Native层的InputDispatcher
mDispatcher = createInputDispatcher(dispatcherPolicy);
mClassifier = new InputClassifier(mDispatcher);
// 创建Native层的InputReader
mReader = createInputReader(readerPolicy, mClassifier);
}

InputManager构造

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 代码位于:frameworks/native/services/inputflinger/InputManager.cpp
* The event flow is via the "InputListener" interface, as follows:
* InputReader -> UnwantedInteractionBlocker -> InputClassifier -> InputDispatcher
*/
InputManager::InputManager(
const sp<InputReaderPolicyInterface>& readerPolicy,
const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {
// 创建Native层的InputDispatcher
mDispatcher = createInputDispatcher(dispatcherPolicy);
mClassifier = std::make_unique<InputClassifier>(*mDispatcher);
mBlocker = std::make_unique<UnwantedInteractionBlocker>(*mClassifier);
// 创建Native层的InputReader
mReader = createInputReader(readerPolicy, *mBlocker);
}

InputManager::crateInputDispatcher

1
2
3
4
5
6
7
/**
* 代码位于:frameworks/native/services/inputflinger/dispatcher/InputDispatcherFactory.cpp
*/
std::unique_ptr<InputDispatcherInterface> createInputDispatcher(
const sp<InputDispatcherPolicyInterface>& policy) {
return std::make_unique<android::inputdispatcher::InputDispatcher>(policy);
}

InputDispatcher构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
: mPolicy(policy),
mPendingEvent(nullptr),
mLastDropReason(DropReason::NOT_DROPPED),
mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
mAppSwitchSawKeyDown(false),
mAppSwitchDueTime(LONG_LONG_MAX),
mNextUnblockedEvent(nullptr),
mDispatchEnabled(false),
mDispatchFrozen(false),
mInputFilterEnabled(false),
// mInTouchMode will be initialized by the WindowManager to the default device config.
// To avoid leaking stack in case that call never comes, and for tests,
// initialize it here anyways.
mInTouchMode(true),
mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
// 创建Looper对象
// 创建属于自己线程的Looper对象;
mLooper = new Looper(false);
mReporter = createInputReporter();

mKeyRepeatState.lastKeyEntry = nullptr;
// 获取分发超时参数
// 超时参数来自于IMS,参数默认值keyRepeatTimeout = 500,keyRepeatDelay = 50。
policy->getDispatcherConfiguration(&mConfig);
}

InputReader构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// --- InputReader ---
/**
* 代码位于:frameworks/native/services/inputflinger/reader/InputReader.cpp
* InputReader的构造函数的实现: 需要传入比较重要的一个EventHub对象
* mQueuedListener的成员变量mInnerListener便是InputDispatcher对象。
*/
InputReader::InputReader(std::shared_ptr<EventHubInterface> eventHub,
const sp<InputReaderPolicyInterface>& policy,
InputListenerInterface& listener)
: mContext(this),
mEventHub(eventHub),
mPolicy(policy),
// 创建输入监听对象
// 此处mQueuedListener的成员变量mInnerListener便是InputDispatcher对象。
mQueuedListener(listener),
mGlobalMetaState(AMETA_NONE),
mLedMetaState(AMETA_NONE),
mGeneration(1),
mNextInputDeviceId(END_RESERVED_ID),
mDisableVirtualKeysTimeout(LLONG_MIN),
mNextTimeout(LLONG_MAX),
mConfigurationChangesToRefresh(0) {
refreshConfigurationLocked(0);
updateGlobalMetaStateLocked();
}

EventHub

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* 代码位于:framework/native/services/inputflinger/reader/EventHub.cpp
* 主要功能:初始化非阻塞式的管道,并添加到epoll
* 创建非阻塞式的读写管道,并且添加到epoll中
**/
EventHub::EventHub(void)
: mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
mNextDeviceId(1),
mControllerNumbers(),
mOpeningDevices(nullptr),
mClosingDevices(nullptr),
mNeedToSendFinishedDeviceScan(false),
mNeedToReopenDevices(false),
mNeedToScanDevices(true),
mPendingEventCount(0),
mPendingEventIndex(0),
mPendingINotify(false) {
ensureProcessCanBlockSuspend();
//创建epoll
mEpollFd = epoll_create1(EPOLL_CLOEXEC);
LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));

mINotifyFd = inotify_init();
//此处DEVICE_PATH为"/dev/input",监听该设备路径
// tatic const char* DEVICE_PATH = "/dev/input";
mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
strerror(errno));
if (isV4lScanningEnabled()) {
mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
VIDEO_DEVICE_PATH, strerror(errno));
} else {
mVideoWd = -1;
ALOGI("Video device scanning disabled");
}

struct epoll_event eventItem = {};
eventItem.events = EPOLLIN | EPOLLWAKEUP;
eventItem.data.fd = mINotifyFd;
// 添加INotify到epoll实例
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 = pipe(wakeFds);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);

mWakeReadPipeFd = wakeFds[0];
mWakeWritePipeFd = wakeFds[1];
//将pipe的读和写都设置为非阻塞方式
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;
//添加管道的读端到epoll实例
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);
}

以上,就是NativeInputManager进行实例化的时候。创建的很多我们在输入数据采集的时候的很多重要的对象。至此。上层的InputManagerService调用nativeInit的方法至此分析。

com_android_server_inputManagerService#nativeStart

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 代码位于:framework/base/service/core/jni/com_android_server_inputManagerService.cpp
* 上层的framework/base/service/core/java/com/android/server/input/InputManagerService.java的执行start的时候回调用
**/
static void nativeStart(JNIEnv* env, jclass /* clazz */, jlong ptr) {
// 将上层转化回来的NativeInputManager的引用。再强制转换为NativeInputManager
NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
// 调用Native层的NativeInputManager的start方法
status_t result = im->getInputManager()->start();
if (result) {
jniThrowRuntimeException(env, "Input manager could not be started.");
}
}

InputManager::start

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
status_t InputManager::start() {
// 启动InputDispatcher的事件分发
status_t result = mDispatcher->start();
if (result) {
ALOGE("Could not start InputDispatcher thread due to error %d.", result);
return result;
}
// 启动InputReader
result = mReader->start();
if (result) {
ALOGE("Could not start InputReader due to error %d.", result);

mDispatcher->stop();
return result;
}

return OK;
}

InputDispatcher::start

1
2
3
4
5
6
7
8
9
status_t InputDispatcher::start() {
if (mThread) {
return ALREADY_EXISTS;
}
// 启动一个InputDispatcher线程
mThread = std::make_unique<InputThread>(
"InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
return OK;
}

InputReader::start

1
2
3
4
5
6
7
8
9
10
11
12
/**
* 代码位于:framework/native/services/inputflinger/reader/InputReader.cpp
**/
status_t InputReader::start() {
if (mThread) {
return ALREADY_EXISTS;
}
// 启动一个InputReader线程
mThread = std::make_unique<InputThread>(
"InputReader", [this]() { loopOnce(); }, [this]() { mEventHub->wake(); });
return OK;
}

InputManager的start方法的主要功能是启动两个线程:

  • 启动线程“InputReader”
  • 启动线程”InputDispatcher“

归纳总结

分层视角:

  1. Java层InputManagerService:采用android.display线程处理Message.
  2. JNI的NativeInputManager:采用android.display线程处理Message,以及创建EventHub。
  3. Native的InputManager:创建InputReaderThread和InputDispatcherThread两个线程

主要功能:

  • IMS服务中的成员变量mPtr记录Native层的NativeInputManager对象;
  • IMS对象的初始化过程的重点在于native初始化,分别创建了以下对象:
    • NativeInputManager;
    • EventHub, InputManager;
    • InputReader,InputDispatcher;
    • InputReaderThread,InputDispatcherThread
  • IMS启动过程的主要功能是启动以下两个线程:
    • InputReader:从EventHub取出事件并处理,再交给InputDispatcher
    • InputDispatcher:接收来自InputReader的输入事件,并派发事件到合适的窗口。

从整个启动过程,可知有system_server进程中有3个线程跟Input输入系统息息相关,分别是android.display, InputReader,InputDispatcher

  • InputDispatcher线程:属于Looper线程,会创建属于自己的Looper,循环分发消息;
  • InputReader线程:通过getEvents()调用EventHub读取输入事件,循环读取消息;
  • android.display线程:属于Looper线程,用于处理Java层的IMS.InputManagerHandler和JNI层的NativeInputManager中指定的MessageHandler消息;