Android 中keyEvent的消息处理

2024-01-02 08:08
文章标签 android 处理 消息 keyevent

本文主要是介绍Android 中keyEvent的消息处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


1. ViewRootImpl.deliverKeyEvent(QueuedInputEvent q)

      1. 如果mView为空或者mAdded为false,就直接调用finishInputEvent。

      2. mView.dispatchKeyEventPreIme(event), 在传递给IME之前做一些预处理。因为对于View来说,如果有输入窗口存在的话,会先将按键消息派发到输入窗口,只有当输入窗口没有处理这个事件,才会派发到真正的视图。因此如果想要在输入法截取事件前处理该消息,则可以重载这个方法去处理一些特定的按键消息。

      3. 如果有IME窗口存在,就把这个传递给IME进行处理。imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);

      4. deliverKeyEventPostIme(q);  将消息派发给真正的视图。

    private void deliverKeyEvent(QueuedInputEvent q) {final KeyEvent event = (KeyEvent)q.mEvent;if (mInputEventConsistencyVerifier != null) {mInputEventConsistencyVerifier.onKeyEvent(event, 0);}if ((q.mFlags & QueuedInputEvent.FLAG_DELIVER_POST_IME) == 0) {// If there is no view, then the event will not be handled.if (mView == null || !mAdded) {finishInputEvent(q, false);return;}if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);// Perform predispatching before the IME.if (mView.dispatchKeyEventPreIme(event)) {finishInputEvent(q, true);return;}// Dispatch to the IME before propagating down the view hierarchy.// The IME will eventually call back into handleImeFinishedEvent.if (mLastWasImTarget) {InputMethodManager imm = InputMethodManager.peekInstance();if (imm != null) {final int seq = event.getSequenceNumber();if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="+ seq + " event=" + event);imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);return;}}}// Not dispatching to IME, continue with post IME actions.deliverKeyEventPostIme(q);}

1.2  ViewRootImpl.deliverKeyEventPostIme(q);

         1. mView.dispatchKeyEvent(event);  将事件派发到View视图。因为mView就是一个DecorView,所以就是调用DecorView的dispatchKeyEvent的方法。

    private void deliverKeyEventPostIme(QueuedInputEvent q) {final KeyEvent event = (KeyEvent)q.mEvent;... ...// If the key's purpose is to exit touch mode then we consume it and consider it handled.if (checkForLeavingTouchModeAndConsume(event)) {finishInputEvent(q, true);return;}// Make sure the fallback event policy sees all keys that will be delivered to the// view hierarchy.mFallbackEventHandler.preDispatchKeyEvent(event);// Deliver the key to the view hierarchy.if (mView.dispatchKeyEvent(event)) {finishInputEvent(q, true);return;}// If the Control modifier is held, try to interpret the key as a shortcut.if (event.getAction() == KeyEvent.ACTION_DOWN&& event.isCtrlPressed()&& event.getRepeatCount() == 0&& !KeyEvent.isModifierKey(event.getKeyCode())) {if (mView.dispatchKeyShortcutEvent(event)) {finishInputEvent(q, true);return;}}// Apply the fallback event policy.if (mFallbackEventHandler.dispatchKeyEvent(event)) {finishInputEvent(q, true);return;}// Handle automatic focus changes.if (event.getAction() == KeyEvent.ACTION_DOWN) {int direction = 0;switch (event.getKeyCode()) {case KeyEvent.KEYCODE_DPAD_LEFT:if (event.hasNoModifiers()) {direction = View.FOCUS_LEFT;}break;case KeyEvent.KEYCODE_DPAD_RIGHT:if (event.hasNoModifiers()) {direction = View.FOCUS_RIGHT;}break;case KeyEvent.KEYCODE_DPAD_UP:if (event.hasNoModifiers()) {direction = View.FOCUS_UP;}break;case KeyEvent.KEYCODE_DPAD_DOWN:if (event.hasNoModifiers()) {direction = View.FOCUS_DOWN;}break;case KeyEvent.KEYCODE_TAB:if (event.hasNoModifiers()) {direction = View.FOCUS_FORWARD;} else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {direction = View.FOCUS_BACKWARD;}break;}if (direction != 0) {View focused = mView.findFocus();if (focused != null) {View v = focused.focusSearch(direction);if (v != null && v != focused) {// do the math the get the interesting rect// of previous focused into the coord system of// newly focused viewfocused.getFocusedRect(mTempRect);if (mView instanceof ViewGroup) {((ViewGroup) mView).offsetDescendantRectToMyCoords(focused, mTempRect);((ViewGroup) mView).offsetRectIntoDescendantCoords(v, mTempRect);}if (v.requestFocus(direction, mTempRect)) {playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));finishInputEvent(q, true);return;}}// Give the focused view a last chance to handle the dpad key.if (mView.dispatchUnhandledMove(focused, direction)) {finishInputEvent(q, true);return;}}}}// Key was unhandled.finishInputEvent(q, false);}

1.2.1 DecorView.dispatchKeyEvent(KeyEvent event)

     1. 如果是Down事件, 首先会判断是不是Shortcut事件也就是快捷键按钮或者特殊事件,如果是就会调用dispatchKeyShortcutEvent和performPanelShortcut进行一些处理然后返回。

     2. 如果不是快捷键按钮,就调用Callback Activity的cb.dispatchKeyEvent(event)去处理。Activity的dispatchKeyEvent中其实也还是去调用PhoneWindow中的superDispatchKeyEvent, PhoneWindow最终还是调用mDecor.superDispatchKeyEvent(event);

        @Overridepublic boolean dispatchKeyEvent(KeyEvent event) {final int keyCode = event.getKeyCode();final int action = event.getAction();final boolean isDown = action == KeyEvent.ACTION_DOWN;if (isDown && (event.getRepeatCount() == 0)) {// First handle chording of panel key: if a panel key is held// but not released, try to execute a shortcut in it.if ((mPanelChordingKey > 0) && (mPanelChordingKey != keyCode)) {boolean handled = dispatchKeyShortcutEvent(event);if (handled) {return true;}}// If a panel is open, perform a shortcut on it without the// chorded panel keyif ((mPreparedPanel != null) && mPreparedPanel.isOpen) {if (performPanelShortcut(mPreparedPanel, keyCode, event, 0)) {return true;}}}if (!isDestroyed()) {final Callback cb = getCallback();final boolean handled = cb != null && mFeatureId < 0 ? cb.dispatchKeyEvent(event): super.dispatchKeyEvent(event);if (handled) {return true;}}return isDown ? PhoneWindow.this.onKeyDown(mFeatureId, event.getKeyCode(), event): PhoneWindow.this.onKeyUp(mFeatureId, event.getKeyCode(), event);}

1.2.1.2 DecorView.mDecor.superDispatchKeyEvent(event);

           1. 调用父类的dispatchKeyEvent。

       public boolean superDispatchKeyEvent(KeyEvent event) {if (super.dispatchKeyEvent(event)) {return true;}// Not handled by the view hierarchy, does the action bar want it// to cancel out of something special?if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {final int action = event.getAction();// Back cancels action modes first.if (mActionMode != null) {if (action == KeyEvent.ACTION_UP) {mActionMode.finish();}return true;}// Next collapse any expanded action views.if (mActionBar != null && mActionBar.hasExpandedActionView()) {if (action == KeyEvent.ACTION_UP) {mActionBar.collapseActionView();}return true;}}return false;}


1.2.1.2.1 ViewGroup.dispatchKeyEvent(KeyEvent event)

        1. mPrivateFlags 是在View中定义的,标志当前View的属性。 这里吧的FOCUSED 和HAS_BOUNDS表示当前的View是否是focused和有bounds的。一般的View和ViewGroup都会有HAS_BOUNDS, 而mFocused记录这当前ViewGroup中处于focus的View。

             例如:如果A包含B,B又包含C,如果C是一个View,C的mPrivateFlags就是 FOCUSED | HAS_BOUNDS那么B的mPrivateFlags就是FOCUSED,mFocused就是C,同理A的mPrivateFlags也是FOCUSED,mFocused就是B。

        2. 所以一般情况下,ViewGroup通过mFocused.dispatchKeyEvent()递归把Event传到View。

    public boolean dispatchKeyEvent(KeyEvent event) {if (mInputEventConsistencyVerifier != null) {mInputEventConsistencyVerifier.onKeyEvent(event, 1);}if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) {if (super.dispatchKeyEvent(event)) {return true;}} else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) {if (mFocused.dispatchKeyEvent(event)) {return true;}}if (mInputEventConsistencyVerifier != null) {mInputEventConsistencyVerifier.onUnhandledEvent(event, 1);}return false;}

1.2.1.2.1.2 View.dispatchKeyEvent()

            如果mFocused是ViewGroup那么还是调用1.2.1.2.1;如果是View,那么就调用View的dispatchKeyEvent。

            1. 如果有注册Listener,就直接调用Listener的onKey去相应,然后返回。

            2. 如果没有注册Listener,就调用KeyEvent.dispatch去做最后的处理

    public boolean dispatchKeyEvent(KeyEvent event) {if (mInputEventConsistencyVerifier != null) {mInputEventConsistencyVerifier.onKeyEvent(event, 0);}// Give any attached key listener a first crack at the event.//noinspection SimplifiableIfStatementListenerInfo li = mListenerInfo;if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED&& li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {return true;}if (event.dispatch(this, mAttachInfo != null? mAttachInfo.mKeyDispatchState : null, this)) {return true;}if (mInputEventConsistencyVerifier != null) {mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);}return false;}

1.2.1.2.1.2.2 KeyEvent.dispatch

        1. KeyEvent.dispatch会根据Action的类型调用receiver的对应的onXXX函数去处理。(receiver通常都是View)

        2. 如果所有的View都没有处理这个KeyEvent,那么会最终通过KeyEvent调用Activity的onXXX函数。

    public final boolean dispatch(Callback receiver, DispatcherState state,Object target) {switch (mAction) {case ACTION_DOWN: {mFlags &= ~FLAG_START_TRACKING;if (DEBUG) Log.v(TAG, "Key down to " + target + " in " + state+ ": " + this);boolean res = receiver.onKeyDown(mKeyCode, this);if (state != null) {if (res && mRepeatCount == 0 && (mFlags&FLAG_START_TRACKING) != 0) {if (DEBUG) Log.v(TAG, "  Start tracking!");state.startTracking(this, target);} else if (isLongPress() && state.isTracking(this)) {try {if (receiver.onKeyLongPress(mKeyCode, this)) {if (DEBUG) Log.v(TAG, "  Clear from long press!");state.performedLongPress(this);res = true;}} catch (AbstractMethodError e) {}}}return res;}case ACTION_UP:if (DEBUG) Log.v(TAG, "Key up to " + target + " in " + state+ ": " + this);if (state != null) {state.handleUpEvent(this);}return receiver.onKeyUp(mKeyCode, this);case ACTION_MULTIPLE:final int count = mRepeatCount;final int code = mKeyCode;if (receiver.onKeyMultiple(code, count, this)) {return true;}if (code != KeyEvent.KEYCODE_UNKNOWN) {mAction = ACTION_DOWN;mRepeatCount = 0;boolean handled = receiver.onKeyDown(code, this);if (handled) {mAction = ACTION_UP;receiver.onKeyUp(code, this);}mAction = ACTION_MULTIPLE;mRepeatCount = count;return handled;}return false;}return false;}













这篇关于Android 中keyEvent的消息处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/561848

相关文章

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

Python进行JSON和Excel文件转换处理指南

《Python进行JSON和Excel文件转换处理指南》在数据交换与系统集成中,JSON与Excel是两种极为常见的数据格式,本文将介绍如何使用Python实现将JSON转换为格式化的Excel文件,... 目录将 jsON 导入为格式化 Excel将 Excel 导出为结构化 JSON处理嵌套 JSON:

Spring Boot 中的默认异常处理机制及执行流程

《SpringBoot中的默认异常处理机制及执行流程》SpringBoot内置BasicErrorController,自动处理异常并生成HTML/JSON响应,支持自定义错误路径、配置及扩展,如... 目录Spring Boot 异常处理机制详解默认错误页面功能自动异常转换机制错误属性配置选项默认错误处理

SpringBoot 异常处理/自定义格式校验的问题实例详解

《SpringBoot异常处理/自定义格式校验的问题实例详解》文章探讨SpringBoot中自定义注解校验问题,区分参数级与类级约束触发的异常类型,建议通过@RestControllerAdvice... 目录1. 问题简要描述2. 异常触发1) 参数级别约束2) 类级别约束3. 异常处理1) 字段级别约束

RabbitMQ消息总线方式刷新配置服务全过程

《RabbitMQ消息总线方式刷新配置服务全过程》SpringCloudBus通过消息总线与MQ实现微服务配置统一刷新,结合GitWebhooks自动触发更新,避免手动重启,提升效率与可靠性,适用于配... 目录前言介绍环境准备代码示例测试验证总结前言介绍在微服务架构中,为了更方便的向微服务实例广播消息,

Java堆转储文件之1.6G大文件处理完整指南

《Java堆转储文件之1.6G大文件处理完整指南》堆转储文件是优化、分析内存消耗的重要工具,:本文主要介绍Java堆转储文件之1.6G大文件处理的相关资料,文中通过代码介绍的非常详细,需要的朋友可... 目录前言文件为什么这么大?如何处理这个文件?分析文件内容(推荐)删除文件(如果不需要)查看错误来源如何避

使用Python构建一个高效的日志处理系统

《使用Python构建一个高效的日志处理系统》这篇文章主要为大家详细讲解了如何使用Python开发一个专业的日志分析工具,能够自动化处理、分析和可视化各类日志文件,大幅提升运维效率,需要的可以了解下... 目录环境准备工具功能概述完整代码实现代码深度解析1. 类设计与初始化2. 日志解析核心逻辑3. 文件处

Java docx4j高效处理Word文档的实战指南

《Javadocx4j高效处理Word文档的实战指南》对于需要在Java应用程序中生成、修改或处理Word文档的开发者来说,docx4j是一个强大而专业的选择,下面我们就来看看docx4j的具体使用... 目录引言一、环境准备与基础配置1.1 Maven依赖配置1.2 初始化测试类二、增强版文档操作示例2.

MyBatis-Plus通用中等、大量数据分批查询和处理方法

《MyBatis-Plus通用中等、大量数据分批查询和处理方法》文章介绍MyBatis-Plus分页查询处理,通过函数式接口与Lambda表达式实现通用逻辑,方法抽象但功能强大,建议扩展分批处理及流式... 目录函数式接口获取分页数据接口数据处理接口通用逻辑工具类使用方法简单查询自定义查询方法总结函数式接口