
目录一、Android事件分类二、InputChannel 注册三、底层读取与分发机制四、按键分发机制五、触摸事件分发机制六、ANR一、Android事件分类1.键盘输入2.触摸事件参考链接键盘输入事件 Android应用程序键盘Keyboard消息处理机制分析android 8按键事件分发机制Android8.0 按键事件处理流程二、InputChannel 注册1.InputReader 循环从 /dev/input/下的硬件节点中读信息 InputDispatcher 分发消息2.ViewRootImpl.setView 中会创建InputChannel 来监听输入事件InputManager.setInputWindows 设置当前获取焦点的WindowWindowManagerService.addWindow中通过InputChannel.openInputChannelPair创建一对输入通道其中一个位于WindowManagerServiceserver端中另外一个通过outInputChannel参数返回到应用程序中client端。InputManager.registerInputChannel 注册InputChannel将server端注册到InputManager最终通过InputDispatcher.registerInputChannel实现注册。2.1 InputReader 为啥不堵塞线程Epoll (I/O 多路复用)无事件时Linux 内核会将该线程挂起阻塞让出 CPU 时间片多线程解耦InputReader负责读取事件InputDispatcher 负责分发WakeFds唤醒机制在需要主动唤醒InputReader的场景下当需要中断当前的epoll_wait()阻塞状态时系统会向wakeFds写入数据epoll监听到该文件描述符有活动从而强制唤醒线程而不必死等外部输入。三、底层读取与分发机制按键与触摸底层逻辑大致相同仅少数地方有说差别。1. InputReader.pollOnce2. EventHub.getEvent3. InputReader.process4. InputReader.consumeEvent5. InputDevice.process6. KeyboardInputMapper.process7. KeyboardInputMapper.processKey8.InputDispatcher.notifyKey--Policy-interceptKeyBeforeQueueing(可供PhoneWindowManager去处理HOME键等特殊按键)--InputDispatcher.dispatchKeyLocked--dispatchEventToCurrentInputTargetsLockedViewRootImpl.enqueueInputEvent--doProcessInputEvents--deliverInputEvent--stage.deliver--apply(NativePreImeInputStage其是由ViewPreImeInputStageImeInputStageEarlyPostImeInputStageNativePostImeInputStageViewPostImeInputStageSyntheticInputStage作为嵌套参数构成的所以调用NativePreImeInputStage的deliver(q)会依次调用到每个InputState的子类的 onProcess()方法)---主要是ViewPostImeInputStage.onProcess四、按键分发机制ViewPostImeInputStage.processKeyEvent这里区分key或触摸事件--mView(DecorView).dispatchKeyEvent--Activity.dispatchKeyEvent--PhoneWindow.dispatchKeyEvent--ViewGroup.dispatchKeyEvent--View.dispatchKeyEvent五、触摸事件分发机制ViewRootImpl.ViewPostImeInputStage.processPointerEvent--deliverPointerEvent--mView.dispatchPointerEvent(该View是Decor.View)--PhoneWindow.dispatchTouchEvent--Activity.dispatchTouchEvent--ViewGroup.dispatchTouchEvent--onInterceptTouchEvent--onTouchEvent。注意事项down事件被一个view拦截后后面的move、up也会被该View处理 。onTouchListener 中的onTouch 优先级高于onTouchEvent, 倘若onTouchListener中的onTouch方法返回trueonTouchEvent会收不到消息。执行顺序onTouch, onTouchEvent, onClick。onclick 依赖于onTouchEvent.六、ANRANR学习总结