讲起事件传递时,都会从Window RootViewImpl 讲起 然后再讲View层的一些处理逻辑,
但传递的事件到底是从哪里来的,当我们触摸屏幕的时候MotionEvent是如何被创建 并传送到目标窗口的,
这里面系统都做了什么呢?
猜想
事件一定有一个从捕获到分发的过程,为了保证实时性因此会有一个线程一直在轮询监听事件,一旦捕获到触摸事件,通过某种规则筛选出所需的窗口,然后通过某种通讯方式分发给所需窗口
一探究竟(基于Android7.1)
我们知道系统服务会在SystemServer中进行实例化操作,我们先将目光放在InputManagerService(以下简称IMS)上,InputManagerService是Android处理各种用户操作抽象的一个服务,是InputManager的真身,在SystemServer中实例化后与WindowManagerService(以下简称WMS)一起添加到ServiceManager中
private void startOtherServices() {
inputManager = new InputManagerService(context);
wm = WindowManagerService.main(context, inputManager,
mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
!mFirstBoot, mOnlyCore);
ServiceManager.addService(Context.WINDOW_SERVICE, wm);
ServiceManager.addService(Context.INPUT_SERVICE, inputManager);
}
由上面代码片段可以看出 IMS与WMS同时被添加进ServiceManager中,WMS有着IMS的引用
有此推断IMS负责触摸事件的捕获,WMS负责将事件派发到目标窗口上。
IMS构造方法中调用nativeInit创建NativeInputManager
NativeInputManager::NativeInputManager(jobject contextObj,
jobject serviceObj, const sp& looper) :
mLooper(looper), mInteractive(true) {
//......
sp eventHub = new EventHub();
mInputManager = new InputManager(eventHub, this, this);
}
这里EventHub 主要负责监听设备事件包括输入设备的拔插,触摸 按钮 鼠标事件等,通过EventHub的getEvents就可以监听并获取该事件,
主要是面向/dev/input 目录下的event设备节点,我们可以用cat 命令查看这些节点,当有输入设备有输入时对应节点会有相应的打印,或者通过getevent命令查看如下
此打印是我 按home键与返回键的打印(如果你此时触摸屏幕会看到跟多打印)
打印为16进制对应过来
66 对应 102 ,9e 对应158
查看 system/usr/keylayout/ 对应关系如下
我们接下来看InputManager,InputManager 创建时伴随创建了 InputDispatcher 与 InputReader 并将
InputDispather 与EventHub传入了InputReader
通过上面可以看到 伴随创建完之后调用了initialize
并开启了两个线程 通过字面意思也可看出
InputReaderThread 负责读取 InputDispatcherThread 负责分发
先来看读取InputReaderThread
InputReaderThread::InputReaderThread(const sp& reader) :
Thread(/*canCallJava*/ true), mReader(reader) {
}
bool InputReaderThread::threadLoop() {
mReader->loopOnce();
return true;
}
void InputReader::loopOnce() {
//获取事件 并处理分发
size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
processEventsLocked(mEventBuffer, count);
//派发 这里的 为在InputManger中穿件传入的 mDispatcher
mQueuedListener->flush();
}
由上可知 InputManager -> initialize
创建一个InputReaderThread ThreadLoop线程 不断的读取输入事件
然后通知 派发 读取流程图如下
接下来看如何分发 InputDispather
在InputManger创建时可知,InputReader传入的mQueuedListener其实就是InputDispatcher对象, 所以mQueuedListener->flush()就是通知InputDispatcher事件读取完毕,可以派发事件了
bool InputDispatcherThread::threadLoop() {
mDispatcher->dispatchOnce();
return true;
}
void InputDispatcher::dispatchOnce() {
{
//被唤醒执行
if (!haveCommandsLocked()) {
dispatchOnceInnerLocked(&nextWakeupTime);
}
}
//睡眠等待事件
mLooper->pollOnce(timeoutMillis);
}
以上就是分发线程的简化代码,dispatchOnceInnerLocked是具体的分发处理逻辑,简化后具体如下
void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
case EventEntry::TYPE_CONFIGURATION_CHANGED: {
ConfigurationChangedEntry* typedEntry =
static_cast(mPendingEvent);
done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
break;
}
case EventEntry::TYPE_DEVICE_RESET: {
DeviceResetEntry* typedEntry =
static_cast(mPendingEvent);
done = dispatchDeviceResetLocked(currentTime, typedEntry);
dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
break;
}
case EventEntry::TYPE_KEY: {
KeyEntry* typedEntry = static_cast(mPendingEvent);
if (isAppSwitchDue) {
if (isAppSwitchKeyEventLocked(typedEntry)) {
resetPendingAppSwitchLocked(true);
isAppSwitchDue = false;
} else if (dropReason == DROP_REASON_NOT_DROPPED) {
dropReason = DROP_REASON_APP_SWITCH;
}
}
if (dropReason == DROP_REASON_NOT_DROPPED
&& isStaleEventLocked(currentTime, typedEntry)) {
dropReason = DROP_REASON_STALE;
}
if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
dropReason = DROP_REASON_BLOCKED;
}
done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
break;
}
case EventEntry::TYPE_MOTION: {
MotionEntry* typedEntry = static_cast(mPendingEvent);
if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
dropReason = DROP_REASON_APP_SWITCH;
}
if (dropReason == DROP_REASON_NOT_DROPPED
&& isStaleEventLocked(currentTime, typedEntry)) {
dropReason = DROP_REASON_STALE;
}
if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
dropReason = DROP_REASON_BLOCKED;
}
done = dispatchMotionLocked(currentTime, typedEntry,
&dropReason, nextWakeupTime);
break;
}
}
}
可以看到,真对不同的类型如 TYPE_MOTION、TYPE_KEY来进行不同的分发,本文探究的是触摸事件,
着重看 TYPE_MOTION 事件的分发 dispatchMotionLocked
bool InputDispatcher::dispatchMotionLocked(
//找到 目标window
injectionResult = findTouchedWindowTargetsLocked(currentTime,
entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
//执行分发
dispatchEventLocked(currentTime, entry, inputTargets);
return true;
}
int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
const MotionEntry* entry, Vector& inputTargets, nsecs_t* nextWakeupTime,
bool* outConflictingPointerActions) {
//遍历所有窗口
size_t numWindows = mWindowHandles.size();
for (size_t i = 0; i < numWindows; i++) {
sp 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
}
}
}
void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
EventEntry* eventEntry, const Vector& inputTargets) {
for (size_t i = 0; i < inputTargets.size(); i++) {
ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
sp connection = mConnectionsByFd.valueAt(connectionIndex);
prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
}
}
}
prepareDispatchCycleLocked()调用 enqueueDispatchEntriesLocked()然后调用
startDispatchCycleLocked
void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
const sp& connection) {
//......
case EventEntry::TYPE_MOTION: {
// Publish the motion event.
status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
motionEntry->deviceId, motionEntry->source,
dispatchEntry->resolvedAction, motionEntry->actionButton,
dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
motionEntry->metaState, motionEntry->buttonState,
xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
motionEntry->downTime, motionEntry->eventTime,
motionEntry->pointerCount, motionEntry->pointerProperties,
usingCoords);
//......
}
}
mWindowHandles为所有窗口,findTouchedWindowTargetsLocked的就是从mWindowHandles中找到目标窗口,规则太复杂,有兴趣可以自行分析。mWindowHandles的值是在InputDispatcher::setInputWindows中传入的,
setInputWindows 由WMS进行调用,WMS中的InputMonitor会间接调用InputDispatcher::setInputWindows,这个时机主要是跟窗口增删等逻辑相关
获取事件与查找窗口已经安排完毕,但到此逻辑都是在SystemServer进程中,SystemServer进程是如何将事件发给应用进程,InputChannel是什么时候创建的,其实应用在setView()的是会调用IWindowSession的addToDisplay()函数。
IWindowSession的具体实现在\services\core\java\com\android\server\wm\Session.java
中
它包含了InputChannel的建立。它本身是个binder
调用,服务端是WMS,最终调用的是WMS的addWindow方法。
InputChannel通过InputChannel.openInputChannelPair分别窗建一对InputChannel,然后将Server端的InputChannel注册到InputDispatcher中,将Client端的InputChannel返回给客户端应用。InputChannel数组的一对InputChannel,一个注册给了InputDispatcher,另一个交给应用程序ViewRootImpl。
public int addWindow(Session session, IWindow client, int seq,
LayoutParams attrs, int viewVisibility, int displayId,
Rect outContentInsets, Rect outStableInsets, Rect outOutsets,
InputChannel outInputChannel) {
.....
WindowState win = new WindowState(this, session, client, token,
attachedWindow, appOp[0], seq, attrs, viewVisibility,
displayContent);
...
if (outInputChannel != null && (attrs.inputFeatures
& LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
String name = win.makeInputChannelName();
//创建
InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);
//服务端InputChannel
win.setInputChannel(inputChannels[0]);
//应用客户端InputChannel
inputChannels[1].transferTo(outInputChannel);
mInputManager.registerInputChannel(win.mInputChannel,
win.mInputWindowHandle);
}
.....
}
//InputTransport.cpp中
status_t InputChannel::openInputChannelPair(const String8& name,
sp& outServerChannel, sp& outClientChannel) {
int sockets[2];
//setsockopt设置socket
int bufferSize = 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));
//创建服务端InputChannel
String8 serverChannelName = name;
serverChannelName.append(" (server)");
outServerChannel = new InputChannel(serverChannelName, sockets[0]);
//创建应用客户端InputChannel
String8 clientChannelName = name;
clientChannelName.append(" (client)");
outClientChannel = new InputChannel(clientChannelName, sockets[1]);
return OK;
}
调用链如下