目录
一、Android事件分类
1.键盘输入;
2.触摸事件:
参考链接:
键盘输入事件: Android应用程序键盘(Keyboard)消息处理机制分析
android 8按键事件分发机制:Android8.0 按键事件处理流程
二、InputChannel 注册:
1.InputReader 循环从 /dev/input/下的硬件节点中读信息, InputDispatcher 分发消息;
2.ViewRootImpl.setView 中会创建InputChannel 来监听输入事件;
InputManager.setInputWindows 设置当前获取焦点的Window
WindowManagerService.addWindow中通过InputChannel.openInputChannelPair创建一对输入通道,其中一个位于WindowManagerService(server端)中,另外一个通过outInputChannel参数返回到应用程序中(client端)。
InputManager.registerInputChannel 注册InputChannel(将server端注册到InputManager),最终通过InputDispatcher.registerInputChannel实现注册。
三、底层读取与分发机制
按键与触摸底层逻辑大致相同,仅少数地方有说差别。
1. InputReader.pollOnce
2. EventHub.getEvent
3. InputReader.process
4. InputReader.consumeEvent
5. InputDevice.process
6. KeyboardInputMapper.process
7. KeyboardInputMapper.processKey
8.InputDispatcher.notifyKey--Policy->interceptKeyBeforeQueueing(可供PhoneWindowManager去处理HOME键等特殊按键)--
InputDispatcher.dispatchKeyLocked--dispatchEventToCurrentInputTargetsLocked
ViewRootImpl.enqueueInputEvent--doProcessInputEvents--deliverInputEvent--stage.deliver--apply(NativePreImeInputStage,其是由ViewPreImeInputStage,ImeInputStage,EarlyPostImeInputStage,NativePostImeInputStage,ViewPostImeInputStage,SyntheticInputStage作为嵌套参数构成的,所以调用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优先级高于onTouchEvent, 倘若onTouchListener中的onTouch方法返回true,onTouchEvent会收不到消息。
执行顺序:onTouch, onTouchEvent, onClick。onclick 依赖于onTouchEvent.