InputManagerService

zhangpan edited this page Aug 28, 2021 · 6 revisions

IMS

IMS是Android为了处理各种用户操作而抽象的一个服务,自身是一个Binder服务实体,在SystemServer进程启动时被初始化并注册到ServiceManager中。这个服务主要是用来提供一些输入设备信息的作用,作为Binder服务的作用比较小

privatevoidstartOtherServices() {
...
// 实例化IMS inputManager = newInputManagerService(context);
// 实例化WMS,并将IMS与WMS关联wm = WindowManagerService.main(context, inputManager,
mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
!mFirstBoot, mOnlyCore);
// WMS注册到ServiceManagerServiceManager.addService(Context.WINDOW_SERVICE, wm);
// IMS注册到ServiceManagerServiceManager.addService(Context.INPUT_SERVICE, inputManager);
...
}

InputManagerService与WIndowManagerService几乎同时被添加,触摸事件的处理也涉及到了这两个服务。WMS持有IMS的引用,IMS负责触摸事件的采集,WMS负责找到目录窗口。

捕获触摸事件

IMS中会单独开一个线程专门读取触摸事件

NativeInputManager::NativeInputManager(jobject contextObj,
jobject serviceObj, const sp<Looper>& looper) :
mLooper(looper), mInteractive(true) {
...
sp<EventHub> eventHub = newEventHub();
mInputManager = newInputManager(eventHub, this, this);
}

EventHub利用Linux的inotify和epoll机制监听设备事件。包括设备插拔以及各种触摸事件、点击事件。可看做一个不同的设备的集线器,主要面向/dev/Input目录下的设备节点,如/dev/input/event0上的事件就是输入事件。通过EventHub的getEvents就可以监听并获取该事件。

InputManager实例化的时候回创建一个InputReader对象,以及InputReaderThread Loop线程。loop线程作用是通过EventHub的getEvents获取Input事件。

InputManager::InputManager(
const sp<EventHubInterface>& eventHub,
const sp<InputReaderPolicyInterface>& readerPolicy,
const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {
<!--事件分发执行类-->
mDispatcher = newInputDispatcher(dispatcherPolicy);
<!--事件读取执行类-->
mReader = newInputReader(eventHub, readerPolicy, mDispatcher);
initialize();
}
voidInputManager::initialize() {
mReaderThread = newInputReaderThread(mReader);
mDispatcherThread = newInputDispatcherThread(mDispatcher);
}
boolInputReaderThread::threadLoop() {
mReader->loopOnce();
returntrue;
}
voidInputReader::loopOnce() {
int32_t oldGeneration;
int32_t timeoutMillis;
bool inputDevicesChanged = false;
Vector<InputDeviceInfo> inputDevices;
{ ...<!--监听事件-->
size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
....<!--处理事件-->
processEventsLocked(mEventBuffer, count);
...
<!--通知派发-->
mQueuedListener->flush();
}

通过上面的流程,输入事件就可以被读取,经过processEventsLocked初步封装成RawEvent,最后发通知,请求派发消息。

事件派发

在InputManager初始化的时候还会创建一个事件派发线程。在事件读取完毕后向派发线程发送一个通知,请派发线程去处理。

InputReader中的mQueueListener是一个InputDispatcher对象,所以mQueuedListener->flush就是通知InputDispatcher事件读取完毕。可以派发事件了。InputDispatcherThead是一个Looper,基于native的Looper实现了Handler消息处理模型。如果有Input事件到来,就唤醒处理事件,处理完毕继续睡眠等待。

boolInputDispatcherThread::threadLoop() {
mDispatcher->dispatchOnce();
returntrue;
}
voidInputDispatcher::dispatchOnce() {
nsecs_t nextWakeupTime = LONG_LONG_MAX;
{ <!--被唤醒 ,处理Input消息-->
if (!haveCommandsLocked()) {
dispatchOnceInnerLocked(&nextWakeupTime);
}
...
} nsecs_t currentTime = now();
int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
<!--睡眠等待input事件-->
mLooper->pollOnce(timeoutMillis);
}

dispatchOnceInnerLocked是具体的派发处理逻辑,看其中的一个分支:

voidInputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
...
case EventEntry::TYPE_MOTION: {
MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
...
done = dispatchMotionLocked(currentTime, typedEntry,
&dropReason, nextWakeupTime);
break;
}
boolInputDispatcher::dispatchMotionLocked(
nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
... Vector<InputTarget> inputTargets;
bool conflictingPointerActions = false;
int32_t injectionResult;
if (isPointerEvent) {
<!--关键点1 找到目标Window-->
injectionResult = findTouchedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
} else {
injectionResult = findFocusedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime);
}
...
<!--关键点2 派发-->
dispatchEventLocked(currentTime, entry, inputTargets);
returntrue;
}

触摸事件会通过findTouchedWindowTargetsLocked找到目标Window,进而通过dispatchEventLocked将消息发送到目标窗口。

查找触摸事件目标窗口

Android系统能够同时支持多块屏幕。每块屏幕都会被抽象成一个DisplayContent,内部维护了一个WindowList列表。用于记录当前屏幕的所有窗口,包括状态栏、导航栏、应用窗口、子窗口等。

如何确定触摸事件对应的窗口是状态栏、导航栏还是应用窗口呢?DisplayContent持有所有窗口信息,因此可以根据触摸事件的位置以及窗口的属性来确定将事件发送到哪个窗口。查找目标窗口的这个过程还跟窗口的状态、透明、分屏等信息有关系:

int32_tInputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
bool* outConflictingPointerActions) {
...
sp<InputWindowHandle> newTouchedWindowHandle;
bool isTouchModal = false;
<!--遍历所有窗口-->
size_t numWindows = mWindowHandles.size();
for (size_t i = 0; i < numWindows; i++) {
sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
const InputWindowInfo* windowInfo = windowHandle->getInfo();
if (windowInfo->displayId != displayId) {
continue; // wrong display
}
int32_t flags = windowInfo->layoutParamsFlags;
if (windowInfo->visible) {
if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
| InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
<!--找到目标窗口-->
if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
newTouchedWindowHandle = windowHandle;
break; // found touched window, exit window loop
}
}
...

这个方法会根据点击位置、窗口z-order等特性从mWindowHandles中找到目标窗口。mWindowHandles是怎么来的?mWindowHandles会在InputDispatcher::setInputWindows中设置的。

voidInputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
...
mWindowHandles = inputWindowHandles;
...
} 

WindowManagerService中的InputMonitor会调用setInputWindows。这个时机主要跟窗口增、改、删除等逻辑相关。如下图:

从上面流程可以理解为什么说WindowManagerService跟InputManagerService是相辅相成的了。

如何将事件发送到窗口上

获取事件和查找目标窗口的逻辑都是在SystemServer进程中的,要通知的目标窗口则是位于APP端的用户进程。所以需要进程间通信,这里使用的是Socket方式实现的。

voidInputDispatcher::dispatchEventLocked(nsecs_t currentTime,
EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
pokeUserActivityLocked(eventEntry);
for (size_t i = 0; i < inputTargets.size(); i++) {
const InputTarget& inputTarget = inputTargets.itemAt(i);
ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
if (connectionIndex >= 0) {
sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
} else {
}
}
}

逐层跟踪代码,最后会调用InputChannel的sendMessage函数,最后通过Socket发送到APP端。

两者通信的Socket是怎么来的?它牵扯到了WindowManagerService,在APP向WMS请求添加窗口的时候,会伴随着Input的创建。窗口的添加一定会调用ViewRootImpl的setView方法。

// ViewRootImplpublicvoidsetView(Viewview, WindowManager.LayoutParamsattrs, ViewpanelParentView) {
...
requestLayout();
if ((mWindowAttributes.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
<!--创建InputChannel容器-->
mInputChannel = newInputChannel();
}
try {
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
<!--添加窗口并请求开辟SocketInput通信通道-->
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
mAttachInfo.mOutsets, mInputChannel);
}...
<!--监听开启Input信道-->
if (mInputChannel != null) {
if (mInputQueueCallback != null) {
mInputQueue = newInputQueue();
mInputQueueCallback.onInputQueueCreated(mInputQueue);
}
mInputEventReceiver = newWindowInputEventReceiver(mInputChannel,
Looper.myLooper());
}

在IwindowSession.aidl定义中InputChannel是out类型,也就是说需要服务端进行填充。服务端WMS填充如下:

publicintaddWindow(Sessionsession, IWindowclient, intseq,
WindowManager.LayoutParamsattrs, intviewVisibility, intdisplayId,
RectoutContentInsets, RectoutStableInsets, RectoutOutsets,
InputChanneloutInputChannel) { ...
if (outInputChannel != null && (attrs.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
Stringname = win.makeInputChannelName();
<!--关键点1创建通信信道 -->
InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);
<!--本地用-->
win.setInputChannel(inputChannels[0]);
<!--APP端用-->
inputChannels[1].transferTo(outInputChannel);
<!--注册信道与窗口-->
mInputManager.registerInputChannel(win.mInputChannel, win.mInputWindowHandle);
}

WMS首先创建socketPair作为全双工通道,并分别填充client与Server的InputChannel中。之后让InputManager将Input通信信道与当前窗口ID绑定,这样就能知道哪个窗口用哪个信道通信了,最后通过BInder将outPutChannel回传到APP端。下面是SocketPair的创建代码:

status_tInputChannel::openInputChannelPair(constString8& name,
sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
intsockets[2];
if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
status_tresult = -errno;
...
returnresult;
}
intbufferSize = SOCKET_BUFFER_SIZE;
setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
<!--填充到serverinputchannel-->
String8serverChannelName = name;
serverChannelName.append(" (server)");
outServerChannel = newInputChannel(serverChannelName, sockets[0]);
<!--填充到clientinputchannel-->
String8clientChannelName = name;
clientChannelName.append(" (client)");
outClientChannel = newInputChannel(clientChannelName, sockets[1]);
returnOK;
}

这里SocketPair的创建与访问其实是借助文件描述符,WMS需要借助Binder通信向APP端回传文件描述符fd,主要是内核层面实现两个进程fd的转换,窗口添加成功后,Socket被创建,被传到APP端。但是通信信道并未完全建立。因为还需要一个主动监听,因为消息到来时需要通知的。

App端监听的手段是将Socket添加到Looper线程的epoll数组中。一有消息到来,Looper线程就会被唤醒。并获取事件内容。从代码来看,通信信道的打开是伴随WindowInputEventReceiver的创建来完成的。

消息到来,Looper根据fd找到对应的监听器NativeInputReceiver,并调用handleEvent处理对应事件。

intNativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) {
...
if (events & ALOOPER_EVENT_INPUT) {
JNIEnv* env = AndroidRuntime::getJNIEnv();
status_t status = consumeEvents(env, false/*consumeBatches*/, -1, NULL);
mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");
return status == OK || status == NO_MEMORY ? 1 : 0;
}
...

之后进一步读取事件并封装成java层对象传递给java层

status_tNativeInputEventReceiver::consumeEvents(JNIEnv* env, bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) { ...
for (;;) { uint32_t seq; InputEvent* inputEvent; <!--获取事件-->
status_t status = mInputConsumer.consume(&mInputEventFactory, consumeBatches, frameTime, &seq, &inputEvent); ...
<!--处理touch事件-->
caseAINPUT_EVENT_TYPE_MOTION: {
MotionEvent* motionEvent = static_cast<MotionEvent*>(inputEvent);
if ((motionEvent->getAction() & AMOTION_EVENT_ACTION_MOVE) && outConsumedBatch) {
*outConsumedBatch = true;
}
inputEventObj = android_view_MotionEvent_obtainAsCopy(env, motionEvent);
break;
} <!--回调处理函数-->
if (inputEventObj) {
env->CallVoidMethod(receiverObj.get(),
gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj);
env->DeleteLocalRef(inputEventObj);
}

触摸事件最终被封装成InputEvent,并通过InputEventReceiver的dispatchInputEvent(WindowInputEventReceiver)进行处理。

后续事件的传递过程参看ViewRootImpl与事件分发

内容来源

十分钟了解Android触摸事件原理(InputManagerService)

公众号:玩转安卓Dev

Java基础

面向对象与Java基础知识

Java集合框架

JVM

多线程与并发

设计模式

Kotlin

Android

项目相关问题

Android基础知识

Android消息机制

Android Binder

View事件分发机制

Android屏幕刷新机制

View的绘制流程

Activity启动

Framework

性能优化

Jetpack&系统View

第三方框架实现原理

计算机网络

算法

Clone this wiki locally

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

InputManagerService

zhangpan edited this page Aug 28, 2021 · 6 revisions

IMS

IMS是Android为了处理各种用户操作而抽象的一个服务,自身是一个Binder服务实体,在SystemServer进程启动时被初始化并注册到ServiceManager中。这个服务主要是用来提供一些输入设备信息的作用,作为Binder服务的作用比较小

privatevoidstartOtherServices() {
...
// 实例化IMS inputManager = newInputManagerService(context);
// 实例化WMS,并将IMS与WMS关联wm = WindowManagerService.main(context, inputManager,
mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
!mFirstBoot, mOnlyCore);
// WMS注册到ServiceManagerServiceManager.addService(Context.WINDOW_SERVICE, wm);
// IMS注册到ServiceManagerServiceManager.addService(Context.INPUT_SERVICE, inputManager);
...
}

InputManagerService与WIndowManagerService几乎同时被添加,触摸事件的处理也涉及到了这两个服务。WMS持有IMS的引用,IMS负责触摸事件的采集,WMS负责找到目录窗口。

捕获触摸事件

IMS中会单独开一个线程专门读取触摸事件

NativeInputManager::NativeInputManager(jobject contextObj,
jobject serviceObj, const sp<Looper>& looper) :
mLooper(looper), mInteractive(true) {
...
sp<EventHub> eventHub = newEventHub();
mInputManager = newInputManager(eventHub, this, this);
}

EventHub利用Linux的inotify和epoll机制监听设备事件。包括设备插拔以及各种触摸事件、点击事件。可看做一个不同的设备的集线器,主要面向/dev/Input目录下的设备节点,如/dev/input/event0上的事件就是输入事件。通过EventHub的getEvents就可以监听并获取该事件。

InputManager实例化的时候回创建一个InputReader对象,以及InputReaderThread Loop线程。loop线程作用是通过EventHub的getEvents获取Input事件。

InputManager::InputManager(
const sp<EventHubInterface>& eventHub,
const sp<InputReaderPolicyInterface>& readerPolicy,
const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {
<!--事件分发执行类-->
mDispatcher = newInputDispatcher(dispatcherPolicy);
<!--事件读取执行类-->
mReader = newInputReader(eventHub, readerPolicy, mDispatcher);
initialize();
}
voidInputManager::initialize() {
mReaderThread = newInputReaderThread(mReader);
mDispatcherThread = newInputDispatcherThread(mDispatcher);
}
boolInputReaderThread::threadLoop() {
mReader->loopOnce();
returntrue;
}
voidInputReader::loopOnce() {
int32_t oldGeneration;
int32_t timeoutMillis;
bool inputDevicesChanged = false;
Vector<InputDeviceInfo> inputDevices;
{ ...<!--监听事件-->
size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
....<!--处理事件-->
processEventsLocked(mEventBuffer, count);
...
<!--通知派发-->
mQueuedListener->flush();
}

通过上面的流程,输入事件就可以被读取,经过processEventsLocked初步封装成RawEvent,最后发通知,请求派发消息。

事件派发

在InputManager初始化的时候还会创建一个事件派发线程。在事件读取完毕后向派发线程发送一个通知,请派发线程去处理。

InputReader中的mQueueListener是一个InputDispatcher对象,所以mQueuedListener->flush就是通知InputDispatcher事件读取完毕。可以派发事件了。InputDispatcherThead是一个Looper,基于native的Looper实现了Handler消息处理模型。如果有Input事件到来,就唤醒处理事件,处理完毕继续睡眠等待。

boolInputDispatcherThread::threadLoop() {
mDispatcher->dispatchOnce();
returntrue;
}
voidInputDispatcher::dispatchOnce() {
nsecs_t nextWakeupTime = LONG_LONG_MAX;
{ <!--被唤醒 ,处理Input消息-->
if (!haveCommandsLocked()) {
dispatchOnceInnerLocked(&nextWakeupTime);
}
...
} nsecs_t currentTime = now();
int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
<!--睡眠等待input事件-->
mLooper->pollOnce(timeoutMillis);
}

dispatchOnceInnerLocked是具体的派发处理逻辑,看其中的一个分支:

voidInputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
...
case EventEntry::TYPE_MOTION: {
MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
...
done = dispatchMotionLocked(currentTime, typedEntry,
&dropReason, nextWakeupTime);
break;
}
boolInputDispatcher::dispatchMotionLocked(
nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
... Vector<InputTarget> inputTargets;
bool conflictingPointerActions = false;
int32_t injectionResult;
if (isPointerEvent) {
<!--关键点1 找到目标Window-->
injectionResult = findTouchedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
} else {
injectionResult = findFocusedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime);
}
...
<!--关键点2 派发-->
dispatchEventLocked(currentTime, entry, inputTargets);
returntrue;
}

触摸事件会通过findTouchedWindowTargetsLocked找到目标Window,进而通过dispatchEventLocked将消息发送到目标窗口。

查找触摸事件目标窗口

Android系统能够同时支持多块屏幕。每块屏幕都会被抽象成一个DisplayContent,内部维护了一个WindowList列表。用于记录当前屏幕的所有窗口,包括状态栏、导航栏、应用窗口、子窗口等。

如何确定触摸事件对应的窗口是状态栏、导航栏还是应用窗口呢?DisplayContent持有所有窗口信息,因此可以根据触摸事件的位置以及窗口的属性来确定将事件发送到哪个窗口。查找目标窗口的这个过程还跟窗口的状态、透明、分屏等信息有关系:

int32_tInputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
bool* outConflictingPointerActions) {
...
sp<InputWindowHandle> newTouchedWindowHandle;
bool isTouchModal = false;
<!--遍历所有窗口-->
size_t numWindows = mWindowHandles.size();
for (size_t i = 0; i < numWindows; i++) {
sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
const InputWindowInfo* windowInfo = windowHandle->getInfo();
if (windowInfo->displayId != displayId) {
continue; // wrong display
}
int32_t flags = windowInfo->layoutParamsFlags;
if (windowInfo->visible) {
if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
| InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
<!--找到目标窗口-->
if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
newTouchedWindowHandle = windowHandle;
break; // found touched window, exit window loop
}
}
...

这个方法会根据点击位置、窗口z-order等特性从mWindowHandles中找到目标窗口。mWindowHandles是怎么来的?mWindowHandles会在InputDispatcher::setInputWindows中设置的。

voidInputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
...
mWindowHandles = inputWindowHandles;
...
} 

WindowManagerService中的InputMonitor会调用setInputWindows。这个时机主要跟窗口增、改、删除等逻辑相关。如下图:

从上面流程可以理解为什么说WindowManagerService跟InputManagerService是相辅相成的了。

如何将事件发送到窗口上

获取事件和查找目标窗口的逻辑都是在SystemServer进程中的,要通知的目标窗口则是位于APP端的用户进程。所以需要进程间通信,这里使用的是Socket方式实现的。

voidInputDispatcher::dispatchEventLocked(nsecs_t currentTime,
EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
pokeUserActivityLocked(eventEntry);
for (size_t i = 0; i < inputTargets.size(); i++) {
const InputTarget& inputTarget = inputTargets.itemAt(i);
ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
if (connectionIndex >= 0) {
sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
} else {
}
}
}

逐层跟踪代码,最后会调用InputChannel的sendMessage函数,最后通过Socket发送到APP端。

两者通信的Socket是怎么来的?它牵扯到了WindowManagerService,在APP向WMS请求添加窗口的时候,会伴随着Input的创建。窗口的添加一定会调用ViewRootImpl的setView方法。

// ViewRootImplpublicvoidsetView(Viewview, WindowManager.LayoutParamsattrs, ViewpanelParentView) {
...
requestLayout();
if ((mWindowAttributes.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
<!--创建InputChannel容器-->
mInputChannel = newInputChannel();
}
try {
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
<!--添加窗口并请求开辟SocketInput通信通道-->
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
mAttachInfo.mOutsets, mInputChannel);
}...
<!--监听开启Input信道-->
if (mInputChannel != null) {
if (mInputQueueCallback != null) {
mInputQueue = newInputQueue();
mInputQueueCallback.onInputQueueCreated(mInputQueue);
}
mInputEventReceiver = newWindowInputEventReceiver(mInputChannel,
Looper.myLooper());
}

在IwindowSession.aidl定义中InputChannel是out类型,也就是说需要服务端进行填充。服务端WMS填充如下:

publicintaddWindow(Sessionsession, IWindowclient, intseq,
WindowManager.LayoutParamsattrs, intviewVisibility, intdisplayId,
RectoutContentInsets, RectoutStableInsets, RectoutOutsets,
InputChanneloutInputChannel) { ...
if (outInputChannel != null && (attrs.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
Stringname = win.makeInputChannelName();
<!--关键点1创建通信信道 -->
InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);
<!--本地用-->
win.setInputChannel(inputChannels[0]);
<!--APP端用-->
inputChannels[1].transferTo(outInputChannel);
<!--注册信道与窗口-->
mInputManager.registerInputChannel(win.mInputChannel, win.mInputWindowHandle);
}

WMS首先创建socketPair作为全双工通道,并分别填充client与Server的InputChannel中。之后让InputManager将Input通信信道与当前窗口ID绑定,这样就能知道哪个窗口用哪个信道通信了,最后通过BInder将outPutChannel回传到APP端。下面是SocketPair的创建代码:

status_tInputChannel::openInputChannelPair(constString8& name,
sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
intsockets[2];
if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
status_tresult = -errno;
...
returnresult;
}
intbufferSize = SOCKET_BUFFER_SIZE;
setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
<!--填充到serverinputchannel-->
String8serverChannelName = name;
serverChannelName.append(" (server)");
outServerChannel = newInputChannel(serverChannelName, sockets[0]);
<!--填充到clientinputchannel-->
String8clientChannelName = name;
clientChannelName.append(" (client)");
outClientChannel = newInputChannel(clientChannelName, sockets[1]);
returnOK;
}

这里SocketPair的创建与访问其实是借助文件描述符,WMS需要借助Binder通信向APP端回传文件描述符fd,主要是内核层面实现两个进程fd的转换,窗口添加成功后,Socket被创建,被传到APP端。但是通信信道并未完全建立。因为还需要一个主动监听,因为消息到来时需要通知的。

App端监听的手段是将Socket添加到Looper线程的epoll数组中。一有消息到来,Looper线程就会被唤醒。并获取事件内容。从代码来看,通信信道的打开是伴随WindowInputEventReceiver的创建来完成的。

消息到来,Looper根据fd找到对应的监听器NativeInputReceiver,并调用handleEvent处理对应事件。

intNativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) {
...
if (events & ALOOPER_EVENT_INPUT) {
JNIEnv* env = AndroidRuntime::getJNIEnv();
status_t status = consumeEvents(env, false/*consumeBatches*/, -1, NULL);
mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");
return status == OK || status == NO_MEMORY ? 1 : 0;
}
...

之后进一步读取事件并封装成java层对象传递给java层

status_tNativeInputEventReceiver::consumeEvents(JNIEnv* env, bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) { ...
for (;;) { uint32_t seq; InputEvent* inputEvent; <!--获取事件-->
status_t status = mInputConsumer.consume(&mInputEventFactory, consumeBatches, frameTime, &seq, &inputEvent); ...
<!--处理touch事件-->
caseAINPUT_EVENT_TYPE_MOTION: {
MotionEvent* motionEvent = static_cast<MotionEvent*>(inputEvent);
if ((motionEvent->getAction() & AMOTION_EVENT_ACTION_MOVE) && outConsumedBatch) {
*outConsumedBatch = true;
}
inputEventObj = android_view_MotionEvent_obtainAsCopy(env, motionEvent);
break;
} <!--回调处理函数-->
if (inputEventObj) {
env->CallVoidMethod(receiverObj.get(),
gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj);
env->DeleteLocalRef(inputEventObj);
}

触摸事件最终被封装成InputEvent,并通过InputEventReceiver的dispatchInputEvent(WindowInputEventReceiver)进行处理。

后续事件的传递过程参看ViewRootImpl与事件分发

内容来源

十分钟了解Android触摸事件原理(InputManagerService)

公众号:玩转安卓Dev

Java基础

面向对象与Java基础知识

Java集合框架

JVM

多线程与并发

设计模式

Kotlin

Android

项目相关问题

Android基础知识

Android消息机制

Android Binder

View事件分发机制

Android屏幕刷新机制

View的绘制流程

Activity启动

Framework

性能优化

Jetpack&系统View

第三方框架实现原理

计算机网络

算法

Clone this wiki locally

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

InputManagerService

zhangpan edited this page Aug 28, 2021 · 6 revisions

IMS

IMS是Android为了处理各种用户操作而抽象的一个服务,自身是一个Binder服务实体,在SystemServer进程启动时被初始化并注册到ServiceManager中。这个服务主要是用来提供一些输入设备信息的作用,作为Binder服务的作用比较小

privatevoidstartOtherServices() {
...
// 实例化IMS inputManager = newInputManagerService(context);
// 实例化WMS,并将IMS与WMS关联wm = WindowManagerService.main(context, inputManager,
mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
!mFirstBoot, mOnlyCore);
// WMS注册到ServiceManagerServiceManager.addService(Context.WINDOW_SERVICE, wm);
// IMS注册到ServiceManagerServiceManager.addService(Context.INPUT_SERVICE, inputManager);
...
}

InputManagerService与WIndowManagerService几乎同时被添加,触摸事件的处理也涉及到了这两个服务。WMS持有IMS的引用,IMS负责触摸事件的采集,WMS负责找到目录窗口。

捕获触摸事件

IMS中会单独开一个线程专门读取触摸事件

NativeInputManager::NativeInputManager(jobject contextObj,
jobject serviceObj, const sp<Looper>& looper) :
mLooper(looper), mInteractive(true) {
...
sp<EventHub> eventHub = newEventHub();
mInputManager = newInputManager(eventHub, this, this);
}

EventHub利用Linux的inotify和epoll机制监听设备事件。包括设备插拔以及各种触摸事件、点击事件。可看做一个不同的设备的集线器,主要面向/dev/Input目录下的设备节点,如/dev/input/event0上的事件就是输入事件。通过EventHub的getEvents就可以监听并获取该事件。

InputManager实例化的时候回创建一个InputReader对象,以及InputReaderThread Loop线程。loop线程作用是通过EventHub的getEvents获取Input事件。

InputManager::InputManager(
const sp<EventHubInterface>& eventHub,
const sp<InputReaderPolicyInterface>& readerPolicy,
const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {
<!--事件分发执行类-->
mDispatcher = newInputDispatcher(dispatcherPolicy);
<!--事件读取执行类-->
mReader = newInputReader(eventHub, readerPolicy, mDispatcher);
initialize();
}
voidInputManager::initialize() {
mReaderThread = newInputReaderThread(mReader);
mDispatcherThread = newInputDispatcherThread(mDispatcher);
}
boolInputReaderThread::threadLoop() {
mReader->loopOnce();
returntrue;
}
voidInputReader::loopOnce() {
int32_t oldGeneration;
int32_t timeoutMillis;
bool inputDevicesChanged = false;
Vector<InputDeviceInfo> inputDevices;
{ ...<!--监听事件-->
size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
....<!--处理事件-->
processEventsLocked(mEventBuffer, count);
...
<!--通知派发-->
mQueuedListener->flush();
}

通过上面的流程,输入事件就可以被读取,经过processEventsLocked初步封装成RawEvent,最后发通知,请求派发消息。

事件派发

在InputManager初始化的时候还会创建一个事件派发线程。在事件读取完毕后向派发线程发送一个通知,请派发线程去处理。

InputReader中的mQueueListener是一个InputDispatcher对象,所以mQueuedListener->flush就是通知InputDispatcher事件读取完毕。可以派发事件了。InputDispatcherThead是一个Looper,基于native的Looper实现了Handler消息处理模型。如果有Input事件到来,就唤醒处理事件,处理完毕继续睡眠等待。

boolInputDispatcherThread::threadLoop() {
mDispatcher->dispatchOnce();
returntrue;
}
voidInputDispatcher::dispatchOnce() {
nsecs_t nextWakeupTime = LONG_LONG_MAX;
{ <!--被唤醒 ,处理Input消息-->
if (!haveCommandsLocked()) {
dispatchOnceInnerLocked(&nextWakeupTime);
}
...
} nsecs_t currentTime = now();
int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
<!--睡眠等待input事件-->
mLooper->pollOnce(timeoutMillis);
}

dispatchOnceInnerLocked是具体的派发处理逻辑,看其中的一个分支:

voidInputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
...
case EventEntry::TYPE_MOTION: {
MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
...
done = dispatchMotionLocked(currentTime, typedEntry,
&dropReason, nextWakeupTime);
break;
}
boolInputDispatcher::dispatchMotionLocked(
nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
... Vector<InputTarget> inputTargets;
bool conflictingPointerActions = false;
int32_t injectionResult;
if (isPointerEvent) {
<!--关键点1 找到目标Window-->
injectionResult = findTouchedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
} else {
injectionResult = findFocusedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime);
}
...
<!--关键点2 派发-->
dispatchEventLocked(currentTime, entry, inputTargets);
returntrue;
}

触摸事件会通过findTouchedWindowTargetsLocked找到目标Window,进而通过dispatchEventLocked将消息发送到目标窗口。

查找触摸事件目标窗口

Android系统能够同时支持多块屏幕。每块屏幕都会被抽象成一个DisplayContent,内部维护了一个WindowList列表。用于记录当前屏幕的所有窗口,包括状态栏、导航栏、应用窗口、子窗口等。

如何确定触摸事件对应的窗口是状态栏、导航栏还是应用窗口呢?DisplayContent持有所有窗口信息,因此可以根据触摸事件的位置以及窗口的属性来确定将事件发送到哪个窗口。查找目标窗口的这个过程还跟窗口的状态、透明、分屏等信息有关系:

int32_tInputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
bool* outConflictingPointerActions) {
...
sp<InputWindowHandle> newTouchedWindowHandle;
bool isTouchModal = false;
<!--遍历所有窗口-->
size_t numWindows = mWindowHandles.size();
for (size_t i = 0; i < numWindows; i++) {
sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
const InputWindowInfo* windowInfo = windowHandle->getInfo();
if (windowInfo->displayId != displayId) {
continue; // wrong display
}
int32_t flags = windowInfo->layoutParamsFlags;
if (windowInfo->visible) {
if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
| InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
<!--找到目标窗口-->
if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
newTouchedWindowHandle = windowHandle;
break; // found touched window, exit window loop
}
}
...

这个方法会根据点击位置、窗口z-order等特性从mWindowHandles中找到目标窗口。mWindowHandles是怎么来的?mWindowHandles会在InputDispatcher::setInputWindows中设置的。

voidInputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
...
mWindowHandles = inputWindowHandles;
...
} 

WindowManagerService中的InputMonitor会调用setInputWindows。这个时机主要跟窗口增、改、删除等逻辑相关。如下图:

从上面流程可以理解为什么说WindowManagerService跟InputManagerService是相辅相成的了。

如何将事件发送到窗口上

获取事件和查找目标窗口的逻辑都是在SystemServer进程中的,要通知的目标窗口则是位于APP端的用户进程。所以需要进程间通信,这里使用的是Socket方式实现的。

voidInputDispatcher::dispatchEventLocked(nsecs_t currentTime,
EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
pokeUserActivityLocked(eventEntry);
for (size_t i = 0; i < inputTargets.size(); i++) {
const InputTarget& inputTarget = inputTargets.itemAt(i);
ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
if (connectionIndex >= 0) {
sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
} else {
}
}
}

逐层跟踪代码,最后会调用InputChannel的sendMessage函数,最后通过Socket发送到APP端。

两者通信的Socket是怎么来的?它牵扯到了WindowManagerService,在APP向WMS请求添加窗口的时候,会伴随着Input的创建。窗口的添加一定会调用ViewRootImpl的setView方法。

// ViewRootImplpublicvoidsetView(Viewview, WindowManager.LayoutParamsattrs, ViewpanelParentView) {
...
requestLayout();
if ((mWindowAttributes.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
<!--创建InputChannel容器-->
mInputChannel = newInputChannel();
}
try {
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
<!--添加窗口并请求开辟SocketInput通信通道-->
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
mAttachInfo.mOutsets, mInputChannel);
}...
<!--监听开启Input信道-->
if (mInputChannel != null) {
if (mInputQueueCallback != null) {
mInputQueue = newInputQueue();
mInputQueueCallback.onInputQueueCreated(mInputQueue);
}
mInputEventReceiver = newWindowInputEventReceiver(mInputChannel,
Looper.myLooper());
}

在IwindowSession.aidl定义中InputChannel是out类型,也就是说需要服务端进行填充。服务端WMS填充如下:

publicintaddWindow(Sessionsession, IWindowclient, intseq,
WindowManager.LayoutParamsattrs, intviewVisibility, intdisplayId,
RectoutContentInsets, RectoutStableInsets, RectoutOutsets,
InputChanneloutInputChannel) { ...
if (outInputChannel != null && (attrs.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
Stringname = win.makeInputChannelName();
<!--关键点1创建通信信道 -->
InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);
<!--本地用-->
win.setInputChannel(inputChannels[0]);
<!--APP端用-->
inputChannels[1].transferTo(outInputChannel);
<!--注册信道与窗口-->
mInputManager.registerInputChannel(win.mInputChannel, win.mInputWindowHandle);
}

WMS首先创建socketPair作为全双工通道,并分别填充client与Server的InputChannel中。之后让InputManager将Input通信信道与当前窗口ID绑定,这样就能知道哪个窗口用哪个信道通信了,最后通过BInder将outPutChannel回传到APP端。下面是SocketPair的创建代码:

status_tInputChannel::openInputChannelPair(constString8& name,
sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
intsockets[2];
if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
status_tresult = -errno;
...
returnresult;
}
intbufferSize = SOCKET_BUFFER_SIZE;
setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
<!--填充到serverinputchannel-->
String8serverChannelName = name;
serverChannelName.append(" (server)");
outServerChannel = newInputChannel(serverChannelName, sockets[0]);
<!--填充到clientinputchannel-->
String8clientChannelName = name;
clientChannelName.append(" (client)");
outClientChannel = newInputChannel(clientChannelName, sockets[1]);
returnOK;
}

这里SocketPair的创建与访问其实是借助文件描述符,WMS需要借助Binder通信向APP端回传文件描述符fd,主要是内核层面实现两个进程fd的转换,窗口添加成功后,Socket被创建,被传到APP端。但是通信信道并未完全建立。因为还需要一个主动监听,因为消息到来时需要通知的。

App端监听的手段是将Socket添加到Looper线程的epoll数组中。一有消息到来,Looper线程就会被唤醒。并获取事件内容。从代码来看,通信信道的打开是伴随WindowInputEventReceiver的创建来完成的。

消息到来,Looper根据fd找到对应的监听器NativeInputReceiver,并调用handleEvent处理对应事件。

intNativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) {
...
if (events & ALOOPER_EVENT_INPUT) {
JNIEnv* env = AndroidRuntime::getJNIEnv();
status_t status = consumeEvents(env, false/*consumeBatches*/, -1, NULL);
mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");
return status == OK || status == NO_MEMORY ? 1 : 0;
}
...

之后进一步读取事件并封装成java层对象传递给java层

status_tNativeInputEventReceiver::consumeEvents(JNIEnv* env, bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) { ...
for (;;) { uint32_t seq; InputEvent* inputEvent; <!--获取事件-->
status_t status = mInputConsumer.consume(&mInputEventFactory, consumeBatches, frameTime, &seq, &inputEvent); ...
<!--处理touch事件-->
caseAINPUT_EVENT_TYPE_MOTION: {
MotionEvent* motionEvent = static_cast<MotionEvent*>(inputEvent);
if ((motionEvent->getAction() & AMOTION_EVENT_ACTION_MOVE) && outConsumedBatch) {
*outConsumedBatch = true;
}
inputEventObj = android_view_MotionEvent_obtainAsCopy(env, motionEvent);
break;
} <!--回调处理函数-->
if (inputEventObj) {
env->CallVoidMethod(receiverObj.get(),
gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj);
env->DeleteLocalRef(inputEventObj);
}

触摸事件最终被封装成InputEvent,并通过InputEventReceiver的dispatchInputEvent(WindowInputEventReceiver)进行处理。

后续事件的传递过程参看ViewRootImpl与事件分发

内容来源

十分钟了解Android触摸事件原理(InputManagerService)

公众号:玩转安卓Dev

Java基础

面向对象与Java基础知识

Java集合框架

JVM

多线程与并发

设计模式

Kotlin

Android

项目相关问题

Android基础知识

Android消息机制

Android Binder

View事件分发机制

Android屏幕刷新机制

View的绘制流程

Activity启动

Framework

性能优化

Jetpack&系统View

第三方框架实现原理

计算机网络

算法

Clone this wiki locally

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

InputManagerService

zhangpan edited this page Aug 28, 2021 · 6 revisions

IMS

IMS是Android为了处理各种用户操作而抽象的一个服务,自身是一个Binder服务实体,在SystemServer进程启动时被初始化并注册到ServiceManager中。这个服务主要是用来提供一些输入设备信息的作用,作为Binder服务的作用比较小

privatevoidstartOtherServices() {
...
// 实例化IMS inputManager = newInputManagerService(context);
// 实例化WMS,并将IMS与WMS关联wm = WindowManagerService.main(context, inputManager,
mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
!mFirstBoot, mOnlyCore);
// WMS注册到ServiceManagerServiceManager.addService(Context.WINDOW_SERVICE, wm);
// IMS注册到ServiceManagerServiceManager.addService(Context.INPUT_SERVICE, inputManager);
...
}

InputManagerService与WIndowManagerService几乎同时被添加,触摸事件的处理也涉及到了这两个服务。WMS持有IMS的引用,IMS负责触摸事件的采集,WMS负责找到目录窗口。

捕获触摸事件

IMS中会单独开一个线程专门读取触摸事件

NativeInputManager::NativeInputManager(jobject contextObj,
jobject serviceObj, const sp<Looper>& looper) :
mLooper(looper), mInteractive(true) {
...
sp<EventHub> eventHub = newEventHub();
mInputManager = newInputManager(eventHub, this, this);
}

EventHub利用Linux的inotify和epoll机制监听设备事件。包括设备插拔以及各种触摸事件、点击事件。可看做一个不同的设备的集线器,主要面向/dev/Input目录下的设备节点,如/dev/input/event0上的事件就是输入事件。通过EventHub的getEvents就可以监听并获取该事件。

InputManager实例化的时候回创建一个InputReader对象,以及InputReaderThread Loop线程。loop线程作用是通过EventHub的getEvents获取Input事件。

InputManager::InputManager(
const sp<EventHubInterface>& eventHub,
const sp<InputReaderPolicyInterface>& readerPolicy,
const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {
<!--事件分发执行类-->
mDispatcher = newInputDispatcher(dispatcherPolicy);
<!--事件读取执行类-->
mReader = newInputReader(eventHub, readerPolicy, mDispatcher);
initialize();
}
voidInputManager::initialize() {
mReaderThread = newInputReaderThread(mReader);
mDispatcherThread = newInputDispatcherThread(mDispatcher);
}
boolInputReaderThread::threadLoop() {
mReader->loopOnce();
returntrue;
}
voidInputReader::loopOnce() {
int32_t oldGeneration;
int32_t timeoutMillis;
bool inputDevicesChanged = false;
Vector<InputDeviceInfo> inputDevices;
{ ...<!--监听事件-->
size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
....<!--处理事件-->
processEventsLocked(mEventBuffer, count);
...
<!--通知派发-->
mQueuedListener->flush();
}

通过上面的流程,输入事件就可以被读取,经过processEventsLocked初步封装成RawEvent,最后发通知,请求派发消息。

事件派发

在InputManager初始化的时候还会创建一个事件派发线程。在事件读取完毕后向派发线程发送一个通知,请派发线程去处理。

InputReader中的mQueueListener是一个InputDispatcher对象,所以mQueuedListener->flush就是通知InputDispatcher事件读取完毕。可以派发事件了。InputDispatcherThead是一个Looper,基于native的Looper实现了Handler消息处理模型。如果有Input事件到来,就唤醒处理事件,处理完毕继续睡眠等待。

boolInputDispatcherThread::threadLoop() {
mDispatcher->dispatchOnce();
returntrue;
}
voidInputDispatcher::dispatchOnce() {
nsecs_t nextWakeupTime = LONG_LONG_MAX;
{ <!--被唤醒 ,处理Input消息-->
if (!haveCommandsLocked()) {
dispatchOnceInnerLocked(&nextWakeupTime);
}
...
} nsecs_t currentTime = now();
int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
<!--睡眠等待input事件-->
mLooper->pollOnce(timeoutMillis);
}

dispatchOnceInnerLocked是具体的派发处理逻辑,看其中的一个分支:

voidInputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
...
case EventEntry::TYPE_MOTION: {
MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
...
done = dispatchMotionLocked(currentTime, typedEntry,
&dropReason, nextWakeupTime);
break;
}
boolInputDispatcher::dispatchMotionLocked(
nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
... Vector<InputTarget> inputTargets;
bool conflictingPointerActions = false;
int32_t injectionResult;
if (isPointerEvent) {
<!--关键点1 找到目标Window-->
injectionResult = findTouchedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
} else {
injectionResult = findFocusedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime);
}
...
<!--关键点2 派发-->
dispatchEventLocked(currentTime, entry, inputTargets);
returntrue;
}

触摸事件会通过findTouchedWindowTargetsLocked找到目标Window,进而通过dispatchEventLocked将消息发送到目标窗口。

查找触摸事件目标窗口

Android系统能够同时支持多块屏幕。每块屏幕都会被抽象成一个DisplayContent,内部维护了一个WindowList列表。用于记录当前屏幕的所有窗口,包括状态栏、导航栏、应用窗口、子窗口等。

如何确定触摸事件对应的窗口是状态栏、导航栏还是应用窗口呢?DisplayContent持有所有窗口信息,因此可以根据触摸事件的位置以及窗口的属性来确定将事件发送到哪个窗口。查找目标窗口的这个过程还跟窗口的状态、透明、分屏等信息有关系:

int32_tInputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
bool* outConflictingPointerActions) {
...
sp<InputWindowHandle> newTouchedWindowHandle;
bool isTouchModal = false;
<!--遍历所有窗口-->
size_t numWindows = mWindowHandles.size();
for (size_t i = 0; i < numWindows; i++) {
sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
const InputWindowInfo* windowInfo = windowHandle->getInfo();
if (windowInfo->displayId != displayId) {
continue; // wrong display
}
int32_t flags = windowInfo->layoutParamsFlags;
if (windowInfo->visible) {
if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
| InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
<!--找到目标窗口-->
if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
newTouchedWindowHandle = windowHandle;
break; // found touched window, exit window loop
}
}
...

这个方法会根据点击位置、窗口z-order等特性从mWindowHandles中找到目标窗口。mWindowHandles是怎么来的?mWindowHandles会在InputDispatcher::setInputWindows中设置的。

voidInputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
...
mWindowHandles = inputWindowHandles;
...
} 

WindowManagerService中的InputMonitor会调用setInputWindows。这个时机主要跟窗口增、改、删除等逻辑相关。如下图:

从上面流程可以理解为什么说WindowManagerService跟InputManagerService是相辅相成的了。

如何将事件发送到窗口上

获取事件和查找目标窗口的逻辑都是在SystemServer进程中的,要通知的目标窗口则是位于APP端的用户进程。所以需要进程间通信,这里使用的是Socket方式实现的。

voidInputDispatcher::dispatchEventLocked(nsecs_t currentTime,
EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
pokeUserActivityLocked(eventEntry);
for (size_t i = 0; i < inputTargets.size(); i++) {
const InputTarget& inputTarget = inputTargets.itemAt(i);
ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
if (connectionIndex >= 0) {
sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
} else {
}
}
}

逐层跟踪代码,最后会调用InputChannel的sendMessage函数,最后通过Socket发送到APP端。

两者通信的Socket是怎么来的?它牵扯到了WindowManagerService,在APP向WMS请求添加窗口的时候,会伴随着Input的创建。窗口的添加一定会调用ViewRootImpl的setView方法。

// ViewRootImplpublicvoidsetView(Viewview, WindowManager.LayoutParamsattrs, ViewpanelParentView) {
...
requestLayout();
if ((mWindowAttributes.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
<!--创建InputChannel容器-->
mInputChannel = newInputChannel();
}
try {
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
<!--添加窗口并请求开辟SocketInput通信通道-->
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
mAttachInfo.mOutsets, mInputChannel);
}...
<!--监听开启Input信道-->
if (mInputChannel != null) {
if (mInputQueueCallback != null) {
mInputQueue = newInputQueue();
mInputQueueCallback.onInputQueueCreated(mInputQueue);
}
mInputEventReceiver = newWindowInputEventReceiver(mInputChannel,
Looper.myLooper());
}

在IwindowSession.aidl定义中InputChannel是out类型,也就是说需要服务端进行填充。服务端WMS填充如下:

publicintaddWindow(Sessionsession, IWindowclient, intseq,
WindowManager.LayoutParamsattrs, intviewVisibility, intdisplayId,
RectoutContentInsets, RectoutStableInsets, RectoutOutsets,
InputChanneloutInputChannel) { ...
if (outInputChannel != null && (attrs.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
Stringname = win.makeInputChannelName();
<!--关键点1创建通信信道 -->
InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);
<!--本地用-->
win.setInputChannel(inputChannels[0]);
<!--APP端用-->
inputChannels[1].transferTo(outInputChannel);
<!--注册信道与窗口-->
mInputManager.registerInputChannel(win.mInputChannel, win.mInputWindowHandle);
}

WMS首先创建socketPair作为全双工通道,并分别填充client与Server的InputChannel中。之后让InputManager将Input通信信道与当前窗口ID绑定,这样就能知道哪个窗口用哪个信道通信了,最后通过BInder将outPutChannel回传到APP端。下面是SocketPair的创建代码:

status_tInputChannel::openInputChannelPair(constString8& name,
sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
intsockets[2];
if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
status_tresult = -errno;
...
returnresult;
}
intbufferSize = SOCKET_BUFFER_SIZE;
setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
<!--填充到serverinputchannel-->
String8serverChannelName = name;
serverChannelName.append(" (server)");
outServerChannel = newInputChannel(serverChannelName, sockets[0]);
<!--填充到clientinputchannel-->
String8clientChannelName = name;
clientChannelName.append(" (client)");
outClientChannel = newInputChannel(clientChannelName, sockets[1]);
returnOK;
}

这里SocketPair的创建与访问其实是借助文件描述符,WMS需要借助Binder通信向APP端回传文件描述符fd,主要是内核层面实现两个进程fd的转换,窗口添加成功后,Socket被创建,被传到APP端。但是通信信道并未完全建立。因为还需要一个主动监听,因为消息到来时需要通知的。

App端监听的手段是将Socket添加到Looper线程的epoll数组中。一有消息到来,Looper线程就会被唤醒。并获取事件内容。从代码来看,通信信道的打开是伴随WindowInputEventReceiver的创建来完成的。

消息到来,Looper根据fd找到对应的监听器NativeInputReceiver,并调用handleEvent处理对应事件。

intNativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) {
...
if (events & ALOOPER_EVENT_INPUT) {
JNIEnv* env = AndroidRuntime::getJNIEnv();
status_t status = consumeEvents(env, false/*consumeBatches*/, -1, NULL);
mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");
return status == OK || status == NO_MEMORY ? 1 : 0;
}
...

之后进一步读取事件并封装成java层对象传递给java层

status_tNativeInputEventReceiver::consumeEvents(JNIEnv* env, bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) { ...
for (;;) { uint32_t seq; InputEvent* inputEvent; <!--获取事件-->
status_t status = mInputConsumer.consume(&mInputEventFactory, consumeBatches, frameTime, &seq, &inputEvent); ...
<!--处理touch事件-->
caseAINPUT_EVENT_TYPE_MOTION: {
MotionEvent* motionEvent = static_cast<MotionEvent*>(inputEvent);
if ((motionEvent->getAction() & AMOTION_EVENT_ACTION_MOVE) && outConsumedBatch) {
*outConsumedBatch = true;
}
inputEventObj = android_view_MotionEvent_obtainAsCopy(env, motionEvent);
break;
} <!--回调处理函数-->
if (inputEventObj) {
env->CallVoidMethod(receiverObj.get(),
gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj);
env->DeleteLocalRef(inputEventObj);
}

触摸事件最终被封装成InputEvent,并通过InputEventReceiver的dispatchInputEvent(WindowInputEventReceiver)进行处理。

后续事件的传递过程参看ViewRootImpl与事件分发

内容来源

十分钟了解Android触摸事件原理(InputManagerService)

公众号:玩转安卓Dev

Java基础

面向对象与Java基础知识

Java集合框架

JVM

多线程与并发

设计模式

Kotlin

Android

项目相关问题

Android基础知识

Android消息机制

Android Binder

View事件分发机制

Android屏幕刷新机制

View的绘制流程

Activity启动

Framework

性能优化

Jetpack&系统View

第三方框架实现原理

计算机网络

算法

Clone this wiki locally

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

InputManagerService

zhangpan edited this page Aug 28, 2021 · 6 revisions

IMS

IMS是Android为了处理各种用户操作而抽象的一个服务,自身是一个Binder服务实体,在SystemServer进程启动时被初始化并注册到ServiceManager中。这个服务主要是用来提供一些输入设备信息的作用,作为Binder服务的作用比较小

privatevoidstartOtherServices() {
...
// 实例化IMS inputManager = newInputManagerService(context);
// 实例化WMS,并将IMS与WMS关联wm = WindowManagerService.main(context, inputManager,
mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
!mFirstBoot, mOnlyCore);
// WMS注册到ServiceManagerServiceManager.addService(Context.WINDOW_SERVICE, wm);
// IMS注册到ServiceManagerServiceManager.addService(Context.INPUT_SERVICE, inputManager);
...
}

InputManagerService与WIndowManagerService几乎同时被添加,触摸事件的处理也涉及到了这两个服务。WMS持有IMS的引用,IMS负责触摸事件的采集,WMS负责找到目录窗口。

捕获触摸事件

IMS中会单独开一个线程专门读取触摸事件

NativeInputManager::NativeInputManager(jobject contextObj,
jobject serviceObj, const sp<Looper>& looper) :
mLooper(looper), mInteractive(true) {
...
sp<EventHub> eventHub = newEventHub();
mInputManager = newInputManager(eventHub, this, this);
}

EventHub利用Linux的inotify和epoll机制监听设备事件。包括设备插拔以及各种触摸事件、点击事件。可看做一个不同的设备的集线器,主要面向/dev/Input目录下的设备节点,如/dev/input/event0上的事件就是输入事件。通过EventHub的getEvents就可以监听并获取该事件。

InputManager实例化的时候回创建一个InputReader对象,以及InputReaderThread Loop线程。loop线程作用是通过EventHub的getEvents获取Input事件。

InputManager::InputManager(
const sp<EventHubInterface>& eventHub,
const sp<InputReaderPolicyInterface>& readerPolicy,
const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {
<!--事件分发执行类-->
mDispatcher = newInputDispatcher(dispatcherPolicy);
<!--事件读取执行类-->
mReader = newInputReader(eventHub, readerPolicy, mDispatcher);
initialize();
}
voidInputManager::initialize() {
mReaderThread = newInputReaderThread(mReader);
mDispatcherThread = newInputDispatcherThread(mDispatcher);
}
boolInputReaderThread::threadLoop() {
mReader->loopOnce();
returntrue;
}
voidInputReader::loopOnce() {
int32_t oldGeneration;
int32_t timeoutMillis;
bool inputDevicesChanged = false;
Vector<InputDeviceInfo> inputDevices;
{ ...<!--监听事件-->
size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
....<!--处理事件-->
processEventsLocked(mEventBuffer, count);
...
<!--通知派发-->
mQueuedListener->flush();
}

通过上面的流程,输入事件就可以被读取,经过processEventsLocked初步封装成RawEvent,最后发通知,请求派发消息。

事件派发

在InputManager初始化的时候还会创建一个事件派发线程。在事件读取完毕后向派发线程发送一个通知,请派发线程去处理。

InputReader中的mQueueListener是一个InputDispatcher对象,所以mQueuedListener->flush就是通知InputDispatcher事件读取完毕。可以派发事件了。InputDispatcherThead是一个Looper,基于native的Looper实现了Handler消息处理模型。如果有Input事件到来,就唤醒处理事件,处理完毕继续睡眠等待。

boolInputDispatcherThread::threadLoop() {
mDispatcher->dispatchOnce();
returntrue;
}
voidInputDispatcher::dispatchOnce() {
nsecs_t nextWakeupTime = LONG_LONG_MAX;
{ <!--被唤醒 ,处理Input消息-->
if (!haveCommandsLocked()) {
dispatchOnceInnerLocked(&nextWakeupTime);
}
...
} nsecs_t currentTime = now();
int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
<!--睡眠等待input事件-->
mLooper->pollOnce(timeoutMillis);
}

dispatchOnceInnerLocked是具体的派发处理逻辑,看其中的一个分支:

voidInputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
...
case EventEntry::TYPE_MOTION: {
MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
...
done = dispatchMotionLocked(currentTime, typedEntry,
&dropReason, nextWakeupTime);
break;
}
boolInputDispatcher::dispatchMotionLocked(
nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
... Vector<InputTarget> inputTargets;
bool conflictingPointerActions = false;
int32_t injectionResult;
if (isPointerEvent) {
<!--关键点1 找到目标Window-->
injectionResult = findTouchedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
} else {
injectionResult = findFocusedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime);
}
...
<!--关键点2 派发-->
dispatchEventLocked(currentTime, entry, inputTargets);
returntrue;
}

触摸事件会通过findTouchedWindowTargetsLocked找到目标Window,进而通过dispatchEventLocked将消息发送到目标窗口。

查找触摸事件目标窗口

Android系统能够同时支持多块屏幕。每块屏幕都会被抽象成一个DisplayContent,内部维护了一个WindowList列表。用于记录当前屏幕的所有窗口,包括状态栏、导航栏、应用窗口、子窗口等。

如何确定触摸事件对应的窗口是状态栏、导航栏还是应用窗口呢?DisplayContent持有所有窗口信息,因此可以根据触摸事件的位置以及窗口的属性来确定将事件发送到哪个窗口。查找目标窗口的这个过程还跟窗口的状态、透明、分屏等信息有关系:

int32_tInputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
bool* outConflictingPointerActions) {
...
sp<InputWindowHandle> newTouchedWindowHandle;
bool isTouchModal = false;
<!--遍历所有窗口-->
size_t numWindows = mWindowHandles.size();
for (size_t i = 0; i < numWindows; i++) {
sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
const InputWindowInfo* windowInfo = windowHandle->getInfo();
if (windowInfo->displayId != displayId) {
continue; // wrong display
}
int32_t flags = windowInfo->layoutParamsFlags;
if (windowInfo->visible) {
if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
| InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
<!--找到目标窗口-->
if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
newTouchedWindowHandle = windowHandle;
break; // found touched window, exit window loop
}
}
...

这个方法会根据点击位置、窗口z-order等特性从mWindowHandles中找到目标窗口。mWindowHandles是怎么来的?mWindowHandles会在InputDispatcher::setInputWindows中设置的。

voidInputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
...
mWindowHandles = inputWindowHandles;
...
} 

WindowManagerService中的InputMonitor会调用setInputWindows。这个时机主要跟窗口增、改、删除等逻辑相关。如下图:

从上面流程可以理解为什么说WindowManagerService跟InputManagerService是相辅相成的了。

如何将事件发送到窗口上

获取事件和查找目标窗口的逻辑都是在SystemServer进程中的,要通知的目标窗口则是位于APP端的用户进程。所以需要进程间通信,这里使用的是Socket方式实现的。

voidInputDispatcher::dispatchEventLocked(nsecs_t currentTime,
EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
pokeUserActivityLocked(eventEntry);
for (size_t i = 0; i < inputTargets.size(); i++) {
const InputTarget& inputTarget = inputTargets.itemAt(i);
ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
if (connectionIndex >= 0) {
sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
} else {
}
}
}

逐层跟踪代码,最后会调用InputChannel的sendMessage函数,最后通过Socket发送到APP端。

两者通信的Socket是怎么来的?它牵扯到了WindowManagerService,在APP向WMS请求添加窗口的时候,会伴随着Input的创建。窗口的添加一定会调用ViewRootImpl的setView方法。

// ViewRootImplpublicvoidsetView(Viewview, WindowManager.LayoutParamsattrs, ViewpanelParentView) {
...
requestLayout();
if ((mWindowAttributes.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
<!--创建InputChannel容器-->
mInputChannel = newInputChannel();
}
try {
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
<!--添加窗口并请求开辟SocketInput通信通道-->
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
mAttachInfo.mOutsets, mInputChannel);
}...
<!--监听开启Input信道-->
if (mInputChannel != null) {
if (mInputQueueCallback != null) {
mInputQueue = newInputQueue();
mInputQueueCallback.onInputQueueCreated(mInputQueue);
}
mInputEventReceiver = newWindowInputEventReceiver(mInputChannel,
Looper.myLooper());
}

在IwindowSession.aidl定义中InputChannel是out类型,也就是说需要服务端进行填充。服务端WMS填充如下:

publicintaddWindow(Sessionsession, IWindowclient, intseq,
WindowManager.LayoutParamsattrs, intviewVisibility, intdisplayId,
RectoutContentInsets, RectoutStableInsets, RectoutOutsets,
InputChanneloutInputChannel) { ...
if (outInputChannel != null && (attrs.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
Stringname = win.makeInputChannelName();
<!--关键点1创建通信信道 -->
InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);
<!--本地用-->
win.setInputChannel(inputChannels[0]);
<!--APP端用-->
inputChannels[1].transferTo(outInputChannel);
<!--注册信道与窗口-->
mInputManager.registerInputChannel(win.mInputChannel, win.mInputWindowHandle);
}

WMS首先创建socketPair作为全双工通道,并分别填充client与Server的InputChannel中。之后让InputManager将Input通信信道与当前窗口ID绑定,这样就能知道哪个窗口用哪个信道通信了,最后通过BInder将outPutChannel回传到APP端。下面是SocketPair的创建代码:

status_tInputChannel::openInputChannelPair(constString8& name,
sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
intsockets[2];
if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
status_tresult = -errno;
...
returnresult;
}
intbufferSize = SOCKET_BUFFER_SIZE;
setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
<!--填充到serverinputchannel-->
String8serverChannelName = name;
serverChannelName.append(" (server)");
outServerChannel = newInputChannel(serverChannelName, sockets[0]);
<!--填充到clientinputchannel-->
String8clientChannelName = name;
clientChannelName.append(" (client)");
outClientChannel = newInputChannel(clientChannelName, sockets[1]);
returnOK;
}

这里SocketPair的创建与访问其实是借助文件描述符,WMS需要借助Binder通信向APP端回传文件描述符fd,主要是内核层面实现两个进程fd的转换,窗口添加成功后,Socket被创建,被传到APP端。但是通信信道并未完全建立。因为还需要一个主动监听,因为消息到来时需要通知的。

App端监听的手段是将Socket添加到Looper线程的epoll数组中。一有消息到来,Looper线程就会被唤醒。并获取事件内容。从代码来看,通信信道的打开是伴随WindowInputEventReceiver的创建来完成的。

消息到来,Looper根据fd找到对应的监听器NativeInputReceiver,并调用handleEvent处理对应事件。

intNativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) {
...
if (events & ALOOPER_EVENT_INPUT) {
JNIEnv* env = AndroidRuntime::getJNIEnv();
status_t status = consumeEvents(env, false/*consumeBatches*/, -1, NULL);
mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");
return status == OK || status == NO_MEMORY ? 1 : 0;
}
...

之后进一步读取事件并封装成java层对象传递给java层

status_tNativeInputEventReceiver::consumeEvents(JNIEnv* env, bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) { ...
for (;;) { uint32_t seq; InputEvent* inputEvent; <!--获取事件-->
status_t status = mInputConsumer.consume(&mInputEventFactory, consumeBatches, frameTime, &seq, &inputEvent); ...
<!--处理touch事件-->
caseAINPUT_EVENT_TYPE_MOTION: {
MotionEvent* motionEvent = static_cast<MotionEvent*>(inputEvent);
if ((motionEvent->getAction() & AMOTION_EVENT_ACTION_MOVE) && outConsumedBatch) {
*outConsumedBatch = true;
}
inputEventObj = android_view_MotionEvent_obtainAsCopy(env, motionEvent);
break;
} <!--回调处理函数-->
if (inputEventObj) {
env->CallVoidMethod(receiverObj.get(),
gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj);
env->DeleteLocalRef(inputEventObj);
}

触摸事件最终被封装成InputEvent,并通过InputEventReceiver的dispatchInputEvent(WindowInputEventReceiver)进行处理。

后续事件的传递过程参看ViewRootImpl与事件分发

内容来源

十分钟了解Android触摸事件原理(InputManagerService)

公众号:玩转安卓Dev

Java基础

面向对象与Java基础知识

Java集合框架

JVM

多线程与并发

设计模式

Kotlin

Android

项目相关问题

Android基础知识

Android消息机制

Android Binder

View事件分发机制

Android屏幕刷新机制

View的绘制流程

Activity启动

Framework

性能优化

Jetpack&系统View

第三方框架实现原理

计算机网络

算法

Clone this wiki locally

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

InputManagerService

zhangpan edited this page Aug 28, 2021 · 6 revisions

IMS

IMS是Android为了处理各种用户操作而抽象的一个服务,自身是一个Binder服务实体,在SystemServer进程启动时被初始化并注册到ServiceManager中。这个服务主要是用来提供一些输入设备信息的作用,作为Binder服务的作用比较小

privatevoidstartOtherServices() {
...
// 实例化IMS inputManager = newInputManagerService(context);
// 实例化WMS,并将IMS与WMS关联wm = WindowManagerService.main(context, inputManager,
mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
!mFirstBoot, mOnlyCore);
// WMS注册到ServiceManagerServiceManager.addService(Context.WINDOW_SERVICE, wm);
// IMS注册到ServiceManagerServiceManager.addService(Context.INPUT_SERVICE, inputManager);
...
}

InputManagerService与WIndowManagerService几乎同时被添加,触摸事件的处理也涉及到了这两个服务。WMS持有IMS的引用,IMS负责触摸事件的采集,WMS负责找到目录窗口。

捕获触摸事件

IMS中会单独开一个线程专门读取触摸事件

NativeInputManager::NativeInputManager(jobject contextObj,
jobject serviceObj, const sp<Looper>& looper) :
mLooper(looper), mInteractive(true) {
...
sp<EventHub> eventHub = newEventHub();
mInputManager = newInputManager(eventHub, this, this);
}

EventHub利用Linux的inotify和epoll机制监听设备事件。包括设备插拔以及各种触摸事件、点击事件。可看做一个不同的设备的集线器,主要面向/dev/Input目录下的设备节点,如/dev/input/event0上的事件就是输入事件。通过EventHub的getEvents就可以监听并获取该事件。

InputManager实例化的时候回创建一个InputReader对象,以及InputReaderThread Loop线程。loop线程作用是通过EventHub的getEvents获取Input事件。

InputManager::InputManager(
const sp<EventHubInterface>& eventHub,
const sp<InputReaderPolicyInterface>& readerPolicy,
const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {
<!--事件分发执行类-->
mDispatcher = newInputDispatcher(dispatcherPolicy);
<!--事件读取执行类-->
mReader = newInputReader(eventHub, readerPolicy, mDispatcher);
initialize();
}
voidInputManager::initialize() {
mReaderThread = newInputReaderThread(mReader);
mDispatcherThread = newInputDispatcherThread(mDispatcher);
}
boolInputReaderThread::threadLoop() {
mReader->loopOnce();
returntrue;
}
voidInputReader::loopOnce() {
int32_t oldGeneration;
int32_t timeoutMillis;
bool inputDevicesChanged = false;
Vector<InputDeviceInfo> inputDevices;
{ ...<!--监听事件-->
size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
....<!--处理事件-->
processEventsLocked(mEventBuffer, count);
...
<!--通知派发-->
mQueuedListener->flush();
}

通过上面的流程,输入事件就可以被读取,经过processEventsLocked初步封装成RawEvent,最后发通知,请求派发消息。

事件派发

在InputManager初始化的时候还会创建一个事件派发线程。在事件读取完毕后向派发线程发送一个通知,请派发线程去处理。

InputReader中的mQueueListener是一个InputDispatcher对象,所以mQueuedListener->flush就是通知InputDispatcher事件读取完毕。可以派发事件了。InputDispatcherThead是一个Looper,基于native的Looper实现了Handler消息处理模型。如果有Input事件到来,就唤醒处理事件,处理完毕继续睡眠等待。

boolInputDispatcherThread::threadLoop() {
mDispatcher->dispatchOnce();
returntrue;
}
voidInputDispatcher::dispatchOnce() {
nsecs_t nextWakeupTime = LONG_LONG_MAX;
{ <!--被唤醒 ,处理Input消息-->
if (!haveCommandsLocked()) {
dispatchOnceInnerLocked(&nextWakeupTime);
}
...
} nsecs_t currentTime = now();
int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
<!--睡眠等待input事件-->
mLooper->pollOnce(timeoutMillis);
}

dispatchOnceInnerLocked是具体的派发处理逻辑,看其中的一个分支:

voidInputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
...
case EventEntry::TYPE_MOTION: {
MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
...
done = dispatchMotionLocked(currentTime, typedEntry,
&dropReason, nextWakeupTime);
break;
}
boolInputDispatcher::dispatchMotionLocked(
nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
... Vector<InputTarget> inputTargets;
bool conflictingPointerActions = false;
int32_t injectionResult;
if (isPointerEvent) {
<!--关键点1 找到目标Window-->
injectionResult = findTouchedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
} else {
injectionResult = findFocusedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime);
}
...
<!--关键点2 派发-->
dispatchEventLocked(currentTime, entry, inputTargets);
returntrue;
}

触摸事件会通过findTouchedWindowTargetsLocked找到目标Window,进而通过dispatchEventLocked将消息发送到目标窗口。

查找触摸事件目标窗口

Android系统能够同时支持多块屏幕。每块屏幕都会被抽象成一个DisplayContent,内部维护了一个WindowList列表。用于记录当前屏幕的所有窗口,包括状态栏、导航栏、应用窗口、子窗口等。

如何确定触摸事件对应的窗口是状态栏、导航栏还是应用窗口呢?DisplayContent持有所有窗口信息,因此可以根据触摸事件的位置以及窗口的属性来确定将事件发送到哪个窗口。查找目标窗口的这个过程还跟窗口的状态、透明、分屏等信息有关系:

int32_tInputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
bool* outConflictingPointerActions) {
...
sp<InputWindowHandle> newTouchedWindowHandle;
bool isTouchModal = false;
<!--遍历所有窗口-->
size_t numWindows = mWindowHandles.size();
for (size_t i = 0; i < numWindows; i++) {
sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
const InputWindowInfo* windowInfo = windowHandle->getInfo();
if (windowInfo->displayId != displayId) {
continue; // wrong display
}
int32_t flags = windowInfo->layoutParamsFlags;
if (windowInfo->visible) {
if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
| InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
<!--找到目标窗口-->
if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
newTouchedWindowHandle = windowHandle;
break; // found touched window, exit window loop
}
}
...

这个方法会根据点击位置、窗口z-order等特性从mWindowHandles中找到目标窗口。mWindowHandles是怎么来的?mWindowHandles会在InputDispatcher::setInputWindows中设置的。

voidInputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
...
mWindowHandles = inputWindowHandles;
...
} 

WindowManagerService中的InputMonitor会调用setInputWindows。这个时机主要跟窗口增、改、删除等逻辑相关。如下图:

从上面流程可以理解为什么说WindowManagerService跟InputManagerService是相辅相成的了。

如何将事件发送到窗口上

获取事件和查找目标窗口的逻辑都是在SystemServer进程中的,要通知的目标窗口则是位于APP端的用户进程。所以需要进程间通信,这里使用的是Socket方式实现的。

voidInputDispatcher::dispatchEventLocked(nsecs_t currentTime,
EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
pokeUserActivityLocked(eventEntry);
for (size_t i = 0; i < inputTargets.size(); i++) {
const InputTarget& inputTarget = inputTargets.itemAt(i);
ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
if (connectionIndex >= 0) {
sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
} else {
}
}
}

逐层跟踪代码,最后会调用InputChannel的sendMessage函数,最后通过Socket发送到APP端。

两者通信的Socket是怎么来的?它牵扯到了WindowManagerService,在APP向WMS请求添加窗口的时候,会伴随着Input的创建。窗口的添加一定会调用ViewRootImpl的setView方法。

// ViewRootImplpublicvoidsetView(Viewview, WindowManager.LayoutParamsattrs, ViewpanelParentView) {
...
requestLayout();
if ((mWindowAttributes.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
<!--创建InputChannel容器-->
mInputChannel = newInputChannel();
}
try {
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
<!--添加窗口并请求开辟SocketInput通信通道-->
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
mAttachInfo.mOutsets, mInputChannel);
}...
<!--监听开启Input信道-->
if (mInputChannel != null) {
if (mInputQueueCallback != null) {
mInputQueue = newInputQueue();
mInputQueueCallback.onInputQueueCreated(mInputQueue);
}
mInputEventReceiver = newWindowInputEventReceiver(mInputChannel,
Looper.myLooper());
}

在IwindowSession.aidl定义中InputChannel是out类型,也就是说需要服务端进行填充。服务端WMS填充如下:

publicintaddWindow(Sessionsession, IWindowclient, intseq,
WindowManager.LayoutParamsattrs, intviewVisibility, intdisplayId,
RectoutContentInsets, RectoutStableInsets, RectoutOutsets,
InputChanneloutInputChannel) { ...
if (outInputChannel != null && (attrs.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
Stringname = win.makeInputChannelName();
<!--关键点1创建通信信道 -->
InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);
<!--本地用-->
win.setInputChannel(inputChannels[0]);
<!--APP端用-->
inputChannels[1].transferTo(outInputChannel);
<!--注册信道与窗口-->
mInputManager.registerInputChannel(win.mInputChannel, win.mInputWindowHandle);
}

WMS首先创建socketPair作为全双工通道,并分别填充client与Server的InputChannel中。之后让InputManager将Input通信信道与当前窗口ID绑定,这样就能知道哪个窗口用哪个信道通信了,最后通过BInder将outPutChannel回传到APP端。下面是SocketPair的创建代码:

status_tInputChannel::openInputChannelPair(constString8& name,
sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
intsockets[2];
if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
status_tresult = -errno;
...
returnresult;
}
intbufferSize = SOCKET_BUFFER_SIZE;
setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
<!--填充到serverinputchannel-->
String8serverChannelName = name;
serverChannelName.append(" (server)");
outServerChannel = newInputChannel(serverChannelName, sockets[0]);
<!--填充到clientinputchannel-->
String8clientChannelName = name;
clientChannelName.append(" (client)");
outClientChannel = newInputChannel(clientChannelName, sockets[1]);
returnOK;
}

这里SocketPair的创建与访问其实是借助文件描述符,WMS需要借助Binder通信向APP端回传文件描述符fd,主要是内核层面实现两个进程fd的转换,窗口添加成功后,Socket被创建,被传到APP端。但是通信信道并未完全建立。因为还需要一个主动监听,因为消息到来时需要通知的。

App端监听的手段是将Socket添加到Looper线程的epoll数组中。一有消息到来,Looper线程就会被唤醒。并获取事件内容。从代码来看,通信信道的打开是伴随WindowInputEventReceiver的创建来完成的。

消息到来,Looper根据fd找到对应的监听器NativeInputReceiver,并调用handleEvent处理对应事件。

intNativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) {
...
if (events & ALOOPER_EVENT_INPUT) {
JNIEnv* env = AndroidRuntime::getJNIEnv();
status_t status = consumeEvents(env, false/*consumeBatches*/, -1, NULL);
mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");
return status == OK || status == NO_MEMORY ? 1 : 0;
}
...

之后进一步读取事件并封装成java层对象传递给java层

status_tNativeInputEventReceiver::consumeEvents(JNIEnv* env, bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) { ...
for (;;) { uint32_t seq; InputEvent* inputEvent; <!--获取事件-->
status_t status = mInputConsumer.consume(&mInputEventFactory, consumeBatches, frameTime, &seq, &inputEvent); ...
<!--处理touch事件-->
caseAINPUT_EVENT_TYPE_MOTION: {
MotionEvent* motionEvent = static_cast<MotionEvent*>(inputEvent);
if ((motionEvent->getAction() & AMOTION_EVENT_ACTION_MOVE) && outConsumedBatch) {
*outConsumedBatch = true;
}
inputEventObj = android_view_MotionEvent_obtainAsCopy(env, motionEvent);
break;
} <!--回调处理函数-->
if (inputEventObj) {
env->CallVoidMethod(receiverObj.get(),
gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj);
env->DeleteLocalRef(inputEventObj);
}

触摸事件最终被封装成InputEvent,并通过InputEventReceiver的dispatchInputEvent(WindowInputEventReceiver)进行处理。

后续事件的传递过程参看ViewRootImpl与事件分发

内容来源

十分钟了解Android触摸事件原理(InputManagerService)

公众号:玩转安卓Dev

Java基础

面向对象与Java基础知识

Java集合框架

JVM

多线程与并发

设计模式

Kotlin

Android

项目相关问题

Android基础知识

Android消息机制

Android Binder

View事件分发机制

Android屏幕刷新机制

View的绘制流程

Activity启动

Framework

性能优化

Jetpack&系统View

第三方框架实现原理

计算机网络

算法

Clone this wiki locally

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

InputManagerService

zhangpan edited this page Aug 28, 2021 · 6 revisions

IMS

IMS是Android为了处理各种用户操作而抽象的一个服务,自身是一个Binder服务实体,在SystemServer进程启动时被初始化并注册到ServiceManager中。这个服务主要是用来提供一些输入设备信息的作用,作为Binder服务的作用比较小

privatevoidstartOtherServices() {
...
// 实例化IMS inputManager = newInputManagerService(context);
// 实例化WMS,并将IMS与WMS关联wm = WindowManagerService.main(context, inputManager,
mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
!mFirstBoot, mOnlyCore);
// WMS注册到ServiceManagerServiceManager.addService(Context.WINDOW_SERVICE, wm);
// IMS注册到ServiceManagerServiceManager.addService(Context.INPUT_SERVICE, inputManager);
...
}

InputManagerService与WIndowManagerService几乎同时被添加,触摸事件的处理也涉及到了这两个服务。WMS持有IMS的引用,IMS负责触摸事件的采集,WMS负责找到目录窗口。

捕获触摸事件

IMS中会单独开一个线程专门读取触摸事件

NativeInputManager::NativeInputManager(jobject contextObj,
jobject serviceObj, const sp<Looper>& looper) :
mLooper(looper), mInteractive(true) {
...
sp<EventHub> eventHub = newEventHub();
mInputManager = newInputManager(eventHub, this, this);
}

EventHub利用Linux的inotify和epoll机制监听设备事件。包括设备插拔以及各种触摸事件、点击事件。可看做一个不同的设备的集线器,主要面向/dev/Input目录下的设备节点,如/dev/input/event0上的事件就是输入事件。通过EventHub的getEvents就可以监听并获取该事件。

InputManager实例化的时候回创建一个InputReader对象,以及InputReaderThread Loop线程。loop线程作用是通过EventHub的getEvents获取Input事件。

InputManager::InputManager(
const sp<EventHubInterface>& eventHub,
const sp<InputReaderPolicyInterface>& readerPolicy,
const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {
<!--事件分发执行类-->
mDispatcher = newInputDispatcher(dispatcherPolicy);
<!--事件读取执行类-->
mReader = newInputReader(eventHub, readerPolicy, mDispatcher);
initialize();
}
voidInputManager::initialize() {
mReaderThread = newInputReaderThread(mReader);
mDispatcherThread = newInputDispatcherThread(mDispatcher);
}
boolInputReaderThread::threadLoop() {
mReader->loopOnce();
returntrue;
}
voidInputReader::loopOnce() {
int32_t oldGeneration;
int32_t timeoutMillis;
bool inputDevicesChanged = false;
Vector<InputDeviceInfo> inputDevices;
{ ...<!--监听事件-->
size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
....<!--处理事件-->
processEventsLocked(mEventBuffer, count);
...
<!--通知派发-->
mQueuedListener->flush();
}

通过上面的流程,输入事件就可以被读取,经过processEventsLocked初步封装成RawEvent,最后发通知,请求派发消息。

事件派发

在InputManager初始化的时候还会创建一个事件派发线程。在事件读取完毕后向派发线程发送一个通知,请派发线程去处理。

InputReader中的mQueueListener是一个InputDispatcher对象,所以mQueuedListener->flush就是通知InputDispatcher事件读取完毕。可以派发事件了。InputDispatcherThead是一个Looper,基于native的Looper实现了Handler消息处理模型。如果有Input事件到来,就唤醒处理事件,处理完毕继续睡眠等待。

boolInputDispatcherThread::threadLoop() {
mDispatcher->dispatchOnce();
returntrue;
}
voidInputDispatcher::dispatchOnce() {
nsecs_t nextWakeupTime = LONG_LONG_MAX;
{ <!--被唤醒 ,处理Input消息-->
if (!haveCommandsLocked()) {
dispatchOnceInnerLocked(&nextWakeupTime);
}
...
} nsecs_t currentTime = now();
int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
<!--睡眠等待input事件-->
mLooper->pollOnce(timeoutMillis);
}

dispatchOnceInnerLocked是具体的派发处理逻辑,看其中的一个分支:

voidInputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
...
case EventEntry::TYPE_MOTION: {
MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
...
done = dispatchMotionLocked(currentTime, typedEntry,
&dropReason, nextWakeupTime);
break;
}
boolInputDispatcher::dispatchMotionLocked(
nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
... Vector<InputTarget> inputTargets;
bool conflictingPointerActions = false;
int32_t injectionResult;
if (isPointerEvent) {
<!--关键点1 找到目标Window-->
injectionResult = findTouchedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
} else {
injectionResult = findFocusedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime);
}
...
<!--关键点2 派发-->
dispatchEventLocked(currentTime, entry, inputTargets);
returntrue;
}

触摸事件会通过findTouchedWindowTargetsLocked找到目标Window,进而通过dispatchEventLocked将消息发送到目标窗口。

查找触摸事件目标窗口

Android系统能够同时支持多块屏幕。每块屏幕都会被抽象成一个DisplayContent,内部维护了一个WindowList列表。用于记录当前屏幕的所有窗口,包括状态栏、导航栏、应用窗口、子窗口等。

如何确定触摸事件对应的窗口是状态栏、导航栏还是应用窗口呢?DisplayContent持有所有窗口信息,因此可以根据触摸事件的位置以及窗口的属性来确定将事件发送到哪个窗口。查找目标窗口的这个过程还跟窗口的状态、透明、分屏等信息有关系:

int32_tInputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
bool* outConflictingPointerActions) {
...
sp<InputWindowHandle> newTouchedWindowHandle;
bool isTouchModal = false;
<!--遍历所有窗口-->
size_t numWindows = mWindowHandles.size();
for (size_t i = 0; i < numWindows; i++) {
sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
const InputWindowInfo* windowInfo = windowHandle->getInfo();
if (windowInfo->displayId != displayId) {
continue; // wrong display
}
int32_t flags = windowInfo->layoutParamsFlags;
if (windowInfo->visible) {
if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
| InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
<!--找到目标窗口-->
if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
newTouchedWindowHandle = windowHandle;
break; // found touched window, exit window loop
}
}
...

这个方法会根据点击位置、窗口z-order等特性从mWindowHandles中找到目标窗口。mWindowHandles是怎么来的?mWindowHandles会在InputDispatcher::setInputWindows中设置的。

voidInputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
...
mWindowHandles = inputWindowHandles;
...
} 

WindowManagerService中的InputMonitor会调用setInputWindows。这个时机主要跟窗口增、改、删除等逻辑相关。如下图:

从上面流程可以理解为什么说WindowManagerService跟InputManagerService是相辅相成的了。

如何将事件发送到窗口上

获取事件和查找目标窗口的逻辑都是在SystemServer进程中的,要通知的目标窗口则是位于APP端的用户进程。所以需要进程间通信,这里使用的是Socket方式实现的。

voidInputDispatcher::dispatchEventLocked(nsecs_t currentTime,
EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
pokeUserActivityLocked(eventEntry);
for (size_t i = 0; i < inputTargets.size(); i++) {
const InputTarget& inputTarget = inputTargets.itemAt(i);
ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
if (connectionIndex >= 0) {
sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
} else {
}
}
}

逐层跟踪代码,最后会调用InputChannel的sendMessage函数,最后通过Socket发送到APP端。

两者通信的Socket是怎么来的?它牵扯到了WindowManagerService,在APP向WMS请求添加窗口的时候,会伴随着Input的创建。窗口的添加一定会调用ViewRootImpl的setView方法。

// ViewRootImplpublicvoidsetView(Viewview, WindowManager.LayoutParamsattrs, ViewpanelParentView) {
...
requestLayout();
if ((mWindowAttributes.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
<!--创建InputChannel容器-->
mInputChannel = newInputChannel();
}
try {
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
<!--添加窗口并请求开辟SocketInput通信通道-->
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
mAttachInfo.mOutsets, mInputChannel);
}...
<!--监听开启Input信道-->
if (mInputChannel != null) {
if (mInputQueueCallback != null) {
mInputQueue = newInputQueue();
mInputQueueCallback.onInputQueueCreated(mInputQueue);
}
mInputEventReceiver = newWindowInputEventReceiver(mInputChannel,
Looper.myLooper());
}

在IwindowSession.aidl定义中InputChannel是out类型,也就是说需要服务端进行填充。服务端WMS填充如下:

publicintaddWindow(Sessionsession, IWindowclient, intseq,
WindowManager.LayoutParamsattrs, intviewVisibility, intdisplayId,
RectoutContentInsets, RectoutStableInsets, RectoutOutsets,
InputChanneloutInputChannel) { ...
if (outInputChannel != null && (attrs.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
Stringname = win.makeInputChannelName();
<!--关键点1创建通信信道 -->
InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);
<!--本地用-->
win.setInputChannel(inputChannels[0]);
<!--APP端用-->
inputChannels[1].transferTo(outInputChannel);
<!--注册信道与窗口-->
mInputManager.registerInputChannel(win.mInputChannel, win.mInputWindowHandle);
}

WMS首先创建socketPair作为全双工通道,并分别填充client与Server的InputChannel中。之后让InputManager将Input通信信道与当前窗口ID绑定,这样就能知道哪个窗口用哪个信道通信了,最后通过BInder将outPutChannel回传到APP端。下面是SocketPair的创建代码:

status_tInputChannel::openInputChannelPair(constString8& name,
sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
intsockets[2];
if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
status_tresult = -errno;
...
returnresult;
}
intbufferSize = SOCKET_BUFFER_SIZE;
setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
<!--填充到serverinputchannel-->
String8serverChannelName = name;
serverChannelName.append(" (server)");
outServerChannel = newInputChannel(serverChannelName, sockets[0]);
<!--填充到clientinputchannel-->
String8clientChannelName = name;
clientChannelName.append(" (client)");
outClientChannel = newInputChannel(clientChannelName, sockets[1]);
returnOK;
}

这里SocketPair的创建与访问其实是借助文件描述符,WMS需要借助Binder通信向APP端回传文件描述符fd,主要是内核层面实现两个进程fd的转换,窗口添加成功后,Socket被创建,被传到APP端。但是通信信道并未完全建立。因为还需要一个主动监听,因为消息到来时需要通知的。

App端监听的手段是将Socket添加到Looper线程的epoll数组中。一有消息到来,Looper线程就会被唤醒。并获取事件内容。从代码来看,通信信道的打开是伴随WindowInputEventReceiver的创建来完成的。

消息到来,Looper根据fd找到对应的监听器NativeInputReceiver,并调用handleEvent处理对应事件。

intNativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) {
...
if (events & ALOOPER_EVENT_INPUT) {
JNIEnv* env = AndroidRuntime::getJNIEnv();
status_t status = consumeEvents(env, false/*consumeBatches*/, -1, NULL);
mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");
return status == OK || status == NO_MEMORY ? 1 : 0;
}
...

之后进一步读取事件并封装成java层对象传递给java层

status_tNativeInputEventReceiver::consumeEvents(JNIEnv* env, bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) { ...
for (;;) { uint32_t seq; InputEvent* inputEvent; <!--获取事件-->
status_t status = mInputConsumer.consume(&mInputEventFactory, consumeBatches, frameTime, &seq, &inputEvent); ...
<!--处理touch事件-->
caseAINPUT_EVENT_TYPE_MOTION: {
MotionEvent* motionEvent = static_cast<MotionEvent*>(inputEvent);
if ((motionEvent->getAction() & AMOTION_EVENT_ACTION_MOVE) && outConsumedBatch) {
*outConsumedBatch = true;
}
inputEventObj = android_view_MotionEvent_obtainAsCopy(env, motionEvent);
break;
} <!--回调处理函数-->
if (inputEventObj) {
env->CallVoidMethod(receiverObj.get(),
gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj);
env->DeleteLocalRef(inputEventObj);
}

触摸事件最终被封装成InputEvent,并通过InputEventReceiver的dispatchInputEvent(WindowInputEventReceiver)进行处理。

后续事件的传递过程参看ViewRootImpl与事件分发

内容来源

十分钟了解Android触摸事件原理(InputManagerService)

公众号:玩转安卓Dev

Java基础

面向对象与Java基础知识

Java集合框架

JVM

多线程与并发

设计模式

Kotlin

Android

项目相关问题

Android基础知识

Android消息机制

Android Binder

View事件分发机制

Android屏幕刷新机制

View的绘制流程

Activity启动

Framework

性能优化

Jetpack&系统View

第三方框架实现原理

计算机网络

算法

Clone this wiki locally

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

InputManagerService

zhangpan edited this page Aug 28, 2021 · 6 revisions

IMS

IMS是Android为了处理各种用户操作而抽象的一个服务,自身是一个Binder服务实体,在SystemServer进程启动时被初始化并注册到ServiceManager中。这个服务主要是用来提供一些输入设备信息的作用,作为Binder服务的作用比较小

privatevoidstartOtherServices() {
...
// 实例化IMS inputManager = newInputManagerService(context);
// 实例化WMS,并将IMS与WMS关联wm = WindowManagerService.main(context, inputManager,
mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
!mFirstBoot, mOnlyCore);
// WMS注册到ServiceManagerServiceManager.addService(Context.WINDOW_SERVICE, wm);
// IMS注册到ServiceManagerServiceManager.addService(Context.INPUT_SERVICE, inputManager);
...
}

InputManagerService与WIndowManagerService几乎同时被添加,触摸事件的处理也涉及到了这两个服务。WMS持有IMS的引用,IMS负责触摸事件的采集,WMS负责找到目录窗口。

捕获触摸事件

IMS中会单独开一个线程专门读取触摸事件

NativeInputManager::NativeInputManager(jobject contextObj,
jobject serviceObj, const sp<Looper>& looper) :
mLooper(looper), mInteractive(true) {
...
sp<EventHub> eventHub = newEventHub();
mInputManager = newInputManager(eventHub, this, this);
}

EventHub利用Linux的inotify和epoll机制监听设备事件。包括设备插拔以及各种触摸事件、点击事件。可看做一个不同的设备的集线器,主要面向/dev/Input目录下的设备节点,如/dev/input/event0上的事件就是输入事件。通过EventHub的getEvents就可以监听并获取该事件。

InputManager实例化的时候回创建一个InputReader对象,以及InputReaderThread Loop线程。loop线程作用是通过EventHub的getEvents获取Input事件。

InputManager::InputManager(
const sp<EventHubInterface>& eventHub,
const sp<InputReaderPolicyInterface>& readerPolicy,
const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {
<!--事件分发执行类-->
mDispatcher = newInputDispatcher(dispatcherPolicy);
<!--事件读取执行类-->
mReader = newInputReader(eventHub, readerPolicy, mDispatcher);
initialize();
}
voidInputManager::initialize() {
mReaderThread = newInputReaderThread(mReader);
mDispatcherThread = newInputDispatcherThread(mDispatcher);
}
boolInputReaderThread::threadLoop() {
mReader->loopOnce();
returntrue;
}
voidInputReader::loopOnce() {
int32_t oldGeneration;
int32_t timeoutMillis;
bool inputDevicesChanged = false;
Vector<InputDeviceInfo> inputDevices;
{ ...<!--监听事件-->
size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
....<!--处理事件-->
processEventsLocked(mEventBuffer, count);
...
<!--通知派发-->
mQueuedListener->flush();
}

通过上面的流程,输入事件就可以被读取,经过processEventsLocked初步封装成RawEvent,最后发通知,请求派发消息。

事件派发

在InputManager初始化的时候还会创建一个事件派发线程。在事件读取完毕后向派发线程发送一个通知,请派发线程去处理。

InputReader中的mQueueListener是一个InputDispatcher对象,所以mQueuedListener->flush就是通知InputDispatcher事件读取完毕。可以派发事件了。InputDispatcherThead是一个Looper,基于native的Looper实现了Handler消息处理模型。如果有Input事件到来,就唤醒处理事件,处理完毕继续睡眠等待。

boolInputDispatcherThread::threadLoop() {
mDispatcher->dispatchOnce();
returntrue;
}
voidInputDispatcher::dispatchOnce() {
nsecs_t nextWakeupTime = LONG_LONG_MAX;
{ <!--被唤醒 ,处理Input消息-->
if (!haveCommandsLocked()) {
dispatchOnceInnerLocked(&nextWakeupTime);
}
...
} nsecs_t currentTime = now();
int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
<!--睡眠等待input事件-->
mLooper->pollOnce(timeoutMillis);
}

dispatchOnceInnerLocked是具体的派发处理逻辑,看其中的一个分支:

voidInputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
...
case EventEntry::TYPE_MOTION: {
MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
...
done = dispatchMotionLocked(currentTime, typedEntry,
&dropReason, nextWakeupTime);
break;
}
boolInputDispatcher::dispatchMotionLocked(
nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
... Vector<InputTarget> inputTargets;
bool conflictingPointerActions = false;
int32_t injectionResult;
if (isPointerEvent) {
<!--关键点1 找到目标Window-->
injectionResult = findTouchedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
} else {
injectionResult = findFocusedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime);
}
...
<!--关键点2 派发-->
dispatchEventLocked(currentTime, entry, inputTargets);
returntrue;
}

触摸事件会通过findTouchedWindowTargetsLocked找到目标Window,进而通过dispatchEventLocked将消息发送到目标窗口。

查找触摸事件目标窗口

Android系统能够同时支持多块屏幕。每块屏幕都会被抽象成一个DisplayContent,内部维护了一个WindowList列表。用于记录当前屏幕的所有窗口,包括状态栏、导航栏、应用窗口、子窗口等。

如何确定触摸事件对应的窗口是状态栏、导航栏还是应用窗口呢?DisplayContent持有所有窗口信息,因此可以根据触摸事件的位置以及窗口的属性来确定将事件发送到哪个窗口。查找目标窗口的这个过程还跟窗口的状态、透明、分屏等信息有关系:

int32_tInputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
bool* outConflictingPointerActions) {
...
sp<InputWindowHandle> newTouchedWindowHandle;
bool isTouchModal = false;
<!--遍历所有窗口-->
size_t numWindows = mWindowHandles.size();
for (size_t i = 0; i < numWindows; i++) {
sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
const InputWindowInfo* windowInfo = windowHandle->getInfo();
if (windowInfo->displayId != displayId) {
continue; // wrong display
}
int32_t flags = windowInfo->layoutParamsFlags;
if (windowInfo->visible) {
if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
| InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
<!--找到目标窗口-->
if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
newTouchedWindowHandle = windowHandle;
break; // found touched window, exit window loop
}
}
...

这个方法会根据点击位置、窗口z-order等特性从mWindowHandles中找到目标窗口。mWindowHandles是怎么来的?mWindowHandles会在InputDispatcher::setInputWindows中设置的。

voidInputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
...
mWindowHandles = inputWindowHandles;
...
} 

WindowManagerService中的InputMonitor会调用setInputWindows。这个时机主要跟窗口增、改、删除等逻辑相关。如下图:

从上面流程可以理解为什么说WindowManagerService跟InputManagerService是相辅相成的了。

如何将事件发送到窗口上

获取事件和查找目标窗口的逻辑都是在SystemServer进程中的,要通知的目标窗口则是位于APP端的用户进程。所以需要进程间通信,这里使用的是Socket方式实现的。

voidInputDispatcher::dispatchEventLocked(nsecs_t currentTime,
EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
pokeUserActivityLocked(eventEntry);
for (size_t i = 0; i < inputTargets.size(); i++) {
const InputTarget& inputTarget = inputTargets.itemAt(i);
ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
if (connectionIndex >= 0) {
sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
} else {
}
}
}

逐层跟踪代码,最后会调用InputChannel的sendMessage函数,最后通过Socket发送到APP端。

两者通信的Socket是怎么来的?它牵扯到了WindowManagerService,在APP向WMS请求添加窗口的时候,会伴随着Input的创建。窗口的添加一定会调用ViewRootImpl的setView方法。

// ViewRootImplpublicvoidsetView(Viewview, WindowManager.LayoutParamsattrs, ViewpanelParentView) {
...
requestLayout();
if ((mWindowAttributes.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
<!--创建InputChannel容器-->
mInputChannel = newInputChannel();
}
try {
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
<!--添加窗口并请求开辟SocketInput通信通道-->
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
mAttachInfo.mOutsets, mInputChannel);
}...
<!--监听开启Input信道-->
if (mInputChannel != null) {
if (mInputQueueCallback != null) {
mInputQueue = newInputQueue();
mInputQueueCallback.onInputQueueCreated(mInputQueue);
}
mInputEventReceiver = newWindowInputEventReceiver(mInputChannel,
Looper.myLooper());
}

在IwindowSession.aidl定义中InputChannel是out类型,也就是说需要服务端进行填充。服务端WMS填充如下:

publicintaddWindow(Sessionsession, IWindowclient, intseq,
WindowManager.LayoutParamsattrs, intviewVisibility, intdisplayId,
RectoutContentInsets, RectoutStableInsets, RectoutOutsets,
InputChanneloutInputChannel) { ...
if (outInputChannel != null && (attrs.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
Stringname = win.makeInputChannelName();
<!--关键点1创建通信信道 -->
InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);
<!--本地用-->
win.setInputChannel(inputChannels[0]);
<!--APP端用-->
inputChannels[1].transferTo(outInputChannel);
<!--注册信道与窗口-->
mInputManager.registerInputChannel(win.mInputChannel, win.mInputWindowHandle);
}

WMS首先创建socketPair作为全双工通道,并分别填充client与Server的InputChannel中。之后让InputManager将Input通信信道与当前窗口ID绑定,这样就能知道哪个窗口用哪个信道通信了,最后通过BInder将outPutChannel回传到APP端。下面是SocketPair的创建代码:

status_tInputChannel::openInputChannelPair(constString8& name,
sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
intsockets[2];
if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
status_tresult = -errno;
...
returnresult;
}
intbufferSize = SOCKET_BUFFER_SIZE;
setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
<!--填充到serverinputchannel-->
String8serverChannelName = name;
serverChannelName.append(" (server)");
outServerChannel = newInputChannel(serverChannelName, sockets[0]);
<!--填充到clientinputchannel-->
String8clientChannelName = name;
clientChannelName.append(" (client)");
outClientChannel = newInputChannel(clientChannelName, sockets[1]);
returnOK;
}

这里SocketPair的创建与访问其实是借助文件描述符,WMS需要借助Binder通信向APP端回传文件描述符fd,主要是内核层面实现两个进程fd的转换,窗口添加成功后,Socket被创建,被传到APP端。但是通信信道并未完全建立。因为还需要一个主动监听,因为消息到来时需要通知的。

App端监听的手段是将Socket添加到Looper线程的epoll数组中。一有消息到来,Looper线程就会被唤醒。并获取事件内容。从代码来看,通信信道的打开是伴随WindowInputEventReceiver的创建来完成的。

消息到来,Looper根据fd找到对应的监听器NativeInputReceiver,并调用handleEvent处理对应事件。

intNativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) {
...
if (events & ALOOPER_EVENT_INPUT) {
JNIEnv* env = AndroidRuntime::getJNIEnv();
status_t status = consumeEvents(env, false/*consumeBatches*/, -1, NULL);
mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");
return status == OK || status == NO_MEMORY ? 1 : 0;
}
...

之后进一步读取事件并封装成java层对象传递给java层

status_tNativeInputEventReceiver::consumeEvents(JNIEnv* env, bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) { ...
for (;;) { uint32_t seq; InputEvent* inputEvent; <!--获取事件-->
status_t status = mInputConsumer.consume(&mInputEventFactory, consumeBatches, frameTime, &seq, &inputEvent); ...
<!--处理touch事件-->
caseAINPUT_EVENT_TYPE_MOTION: {
MotionEvent* motionEvent = static_cast<MotionEvent*>(inputEvent);
if ((motionEvent->getAction() & AMOTION_EVENT_ACTION_MOVE) && outConsumedBatch) {
*outConsumedBatch = true;
}
inputEventObj = android_view_MotionEvent_obtainAsCopy(env, motionEvent);
break;
} <!--回调处理函数-->
if (inputEventObj) {
env->CallVoidMethod(receiverObj.get(),
gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj);
env->DeleteLocalRef(inputEventObj);
}

触摸事件最终被封装成InputEvent,并通过InputEventReceiver的dispatchInputEvent(WindowInputEventReceiver)进行处理。

后续事件的传递过程参看ViewRootImpl与事件分发

内容来源

十分钟了解Android触摸事件原理(InputManagerService)

公众号:玩转安卓Dev

Java基础

面向对象与Java基础知识

Java集合框架

JVM

多线程与并发

设计模式

Kotlin

Android

项目相关问题

Android基础知识

Android消息机制

Android Binder

View事件分发机制

Android屏幕刷新机制

View的绘制流程

Activity启动

Framework

性能优化

Jetpack&系统View

第三方框架实现原理

计算机网络

算法

Clone this wiki locally