Android4.1中会被系统拦截的InputEent

2024-01-02 08:08

本文主要是介绍Android4.1中会被系统拦截的InputEent,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


1. InputDispatcher::notifyKey

     如果系统发现一个Event是KeyEvent, 会调用nofityKey去通知收到一个KeyEvent. 在notifyKey中会查看policy的策略。 

     mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);  //mPolicy实际上就是 NativeInputManager。  当这个函数执行后会把对应的policy也设置到poicyFlags里面。

    

2. NativeInputManager::interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags) 

     NativeInputManager是一个JNI类,自己不做什么工作,只是通过env->CallIntMethod(mServiceObj, gServiceClassInfo.interceptKeyBeforeQueueing, keyEventObj, policyFlags, isScreenOn); 去调用Java的interceptKeyBeforeQueueing方法。 实际上就是调用 InputManagerService.interceptKeyBeforeQueueing()


3. InputManagerService.interceptKeyBeforeQueueing()

    // Native callback.private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {return mCallbacks.interceptKeyBeforeQueueing(event, policyFlags, isScreenOn);}
   可以看到里面只是调用了回到函数而已,而mCallbacks就是InputMoniter.java

4. InputMoniter.interceptKeyBeforeQueueing()

    /* Provides an opportunity for the window manager policy to intercept early key* processing as soon as the key has been read from the device. */public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {Slog.d("InputMonitor.java", "interceptKeyBeforeQueueing !!!!!!");return mService.mPolicy.interceptKeyBeforeQueueing(event, policyFlags, isScreenOn);}

5. mService.mPolicy.interceptKeyBeforeQueueing(event, policyFlags, isScreenOn);

    // Native callback.private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {Slog.d("InputManagerService.java", "interceptKeyBeforeQueueing !!!!!!!!!!!!!!");return mCallbacks.interceptKeyBeforeQueueing(event, policyFlags, isScreenOn);}
    InputMoniter.interceptKeyBeforeQueueing()中就是直接调了mService.mPolicy.interceptKeyBeforeQueueing, mService是WindowManagerService, mPolicy是PhoneWindowManager. 简而言之就是会去直走到PhoneWindowManager中。


6. PhoneWindowManager.interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) 

    

     代码很长,需要慢慢分析。


7.  InputDispatcher::dispatchKeyLocked

     当InputDispatcher::notifyKey 完成之后,InputDispatcher就会调用dispatchKeyLocked去做进一步的分配。

      一个Event过来都是通过InputDispatcher进行分发的,在dispatchKeyLocked中会调用 InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible 去

     

bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,DropReason* dropReason, nsecs_t* nextWakeupTime) {// Preprocessing.// Give the policy a chance to intercept the key.if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {CommandEntry* commandEntry = postCommandLocked(& InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);... ...} else {entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;}} else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {... ...}// Dispatch the key.dispatchEventLocked(currentTime, entry, inputTargets);return true;
}

8. InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible

    在这个函数中哦你依旧还是通过mPolicy(NativeInputManager)去通过JNI调用InputManagerService. 

void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry) {... ...nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,&event, entry->policyFlags);mLock.lock();if (delay < 0) {entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;} else if (!delay) {entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;} else {entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;entry->interceptKeyWakeupTime = now() + delay;}entry->release();
}

 9. NativeInputManager::interceptKeyBeforeDispatching

nsecs_t NativeInputManager::interceptKeyBeforeDispatching(const sp<InputWindowHandle>& inputWindowHandle,const KeyEvent* keyEvent, uint32_t policyFlags) {// Policy:// - Ignore untrusted events and pass them along.// - Filter normal events and trusted injected events through the window manager policy to//   handle the HOME key and the like.nsecs_t result = 0;if (policyFlags & POLICY_FLAG_TRUSTED) {jobject inputWindowHandleObj = getInputWindowHandleObjLocalRef(env, inputWindowHandle);jobject keyEventObj = android_view_KeyEvent_fromNative(env, keyEvent);if (keyEventObj) {jlong delayMillis = env->CallLongMethod(mServiceObj,gServiceClassInfo.interceptKeyBeforeDispatching,inputWindowHandleObj, keyEventObj, policyFlags);} env->DeleteLocalRef(inputWindowHandleObj);}return result;
}

 10. InputManagerService.intercepKeyBeforeDispatching()
    // Native callback.private long interceptKeyBeforeDispatching(InputWindowHandle focus,KeyEvent event, int policyFlags) {return mCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);}

11. InputMonitor.interceptKeyBeforeDispatching()

    /* Provides an opportunity for the window manager policy to process a key before* ordinary dispatch. */public long interceptKeyBeforeDispatching(InputWindowHandle focus, KeyEvent event, int policyFlags) {Log.d("InputMonitor.java","interceptKeyBeforeDispatching !!!!!!");WindowState windowState = focus != null ? (WindowState) focus.windowState : null;return mService.mPolicy.interceptKeyBeforeDispatching(windowState, event, policyFlags);}


12. PhoneWondowManager.interceptKeyBeforeDispatching()
   public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) {final boolean keyguardOn = keyguardOn();final int keyCode = event.getKeyCode();final int repeatCount = event.getRepeatCount();final int metaState = event.getMetaState();final int flags = event.getFlags();final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;final boolean canceled = event.isCanceled();if (DEBUG_INPUT) {Log.d(TAG, "interceptKeyTi keyCode=" + keyCode + " down=" + down + " repeatCount="+ repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed+ " canceled=" + canceled);}// If we think we might have a volume down & power key chord on the way// but we're not sure, then tell the dispatcher to wait a little while and// try again later before dispatching.if (mScreenshotChordEnabled && (flags & KeyEvent.FLAG_FALLBACK) == 0) {if (mVolumeDownKeyTriggered && !mPowerKeyTriggered) {final long now = SystemClock.uptimeMillis();final long timeoutTime = mVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS;if (now < timeoutTime) {return timeoutTime - now;}}if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN&& mVolumeDownKeyConsumedByScreenshotChord) {if (!down) {mVolumeDownKeyConsumedByScreenshotChord = false;}return -1;}}// First we always handle the home key here, so applications// can never break it, although if keyguard is on, we do let// it handle it, because that gives us the correct 5 second// timeout.if (keyCode == KeyEvent.KEYCODE_HOME) {// If we have released the home key, and didn't do anything else// while it was pressed, then it is time to go home!if (!down) {final boolean homeWasLongPressed = mHomeLongPressed;mHomePressed = false;mHomeLongPressed = false;if (!homeWasLongPressed) {try {IStatusBarService statusbar = getStatusBarService();if (statusbar != null) {statusbar.cancelPreloadRecentApps();}} catch (RemoteException e) {Slog.e(TAG, "RemoteException when showing recent apps", e);// re-acquire status bar service next time it is needed.mStatusBarService = null;}mHomePressed = false;if (!canceled) {// If an incoming call is ringing, HOME is totally disabled.// (The user is already on the InCallScreen at this point,// and his ONLY options are to answer or reject the call.)boolean incomingRinging = false;try {ITelephony telephonyService = getTelephonyService();if (telephonyService != null) {incomingRinging = telephonyService.isRinging();}} catch (RemoteException ex) {Log.w(TAG, "RemoteException from getPhoneInterface()", ex);}if (incomingRinging) {Log.i(TAG, "Ignoring HOME; there's a ringing incoming call.");} else {launchHomeFromHotKey();  //launch home}} else {Log.i(TAG, "Ignoring HOME; event canceled.");}return -1;}}// If a system window has focus, then it doesn't make sense// right now to interact with applications.WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;if (attrs != null) {final int type = attrs.type;if (type == WindowManager.LayoutParams.TYPE_KEYGUARD|| type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) {// the "app" is keyguard, so give it the keyreturn 0;}final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;for (int i=0; i<typeCount; i++) {if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {// don't do anything, but also don't pass it to the appreturn -1;}}}if (down) {if (!mHomePressed && mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) {try {IStatusBarService statusbar = getStatusBarService();if (statusbar != null) {statusbar.preloadRecentApps();}} catch (RemoteException e) {Slog.e(TAG, "RemoteException when preloading recent apps", e);// re-acquire status bar service next time it is needed.mStatusBarService = null;}}if (repeatCount == 0) {mHomePressed = true;} else if ((event.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) {if (!keyguardOn) {handleLongPressOnHome();}}}return -1;} else if (keyCode == KeyEvent.KEYCODE_MENU) {// Hijack modified menu keys for debugging featuresfinal int chordBug = KeyEvent.META_SHIFT_ON;if (down && repeatCount == 0) {if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) {Intent intent = new Intent(Intent.ACTION_BUG_REPORT);mContext.sendOrderedBroadcast(intent, null);return -1;} else if (SHOW_PROCESSES_ON_ALT_MENU &&(metaState & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) {Intent service = new Intent();service.setClassName(mContext, "com.android.server.LoadAverageService");ContentResolver res = mContext.getContentResolver();boolean shown = Settings.System.getInt(res, Settings.System.SHOW_PROCESSES, 0) != 0;if (!shown) {mContext.startService(service);} else {mContext.stopService(service);}Settings.System.putInt(res, Settings.System.SHOW_PROCESSES, shown ? 0 : 1);return -1;}}} else if (keyCode == KeyEvent.KEYCODE_SEARCH) {if (down) {if (repeatCount == 0) {mSearchKeyShortcutPending = true;mConsumeSearchKeyUp = false;}} else {mSearchKeyShortcutPending = false;if (mConsumeSearchKeyUp) {mConsumeSearchKeyUp = false;return -1;}}return 0;} else if (keyCode == KeyEvent.KEYCODE_APP_SWITCH) {if (down && repeatCount == 0 && !keyguardOn) {showOrHideRecentAppsDialog(RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS);}return -1;} else if (keyCode == KeyEvent.KEYCODE_ASSIST) {if (down) {if (repeatCount == 0) {mAssistKeyLongPressed = false;} else if (repeatCount == 1) {mAssistKeyLongPressed = true;if (!keyguardOn) {launchAssistLongPressAction();}}} else {if (mAssistKeyLongPressed) {mAssistKeyLongPressed = false;} else {if (!keyguardOn) {launchAssistAction();}}}return -1;}// Shortcuts are invoked through Search+key, so intercept those here// Any printing key that is chorded with Search should be consumed// even if no shortcut was invoked.  This prevents text from being// inadvertently inserted when using a keyboard that has built-in macro// shortcut keys (that emit Search+x) and some of them are not registered.if (mSearchKeyShortcutPending) {final KeyCharacterMap kcm = event.getKeyCharacterMap();if (kcm.isPrintingKey(keyCode)) {mConsumeSearchKeyUp = true;mSearchKeyShortcutPending = false;if (down && repeatCount == 0 && !keyguardOn) {Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState);if (shortcutIntent != null) {shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);try {mContext.startActivity(shortcutIntent);} catch (ActivityNotFoundException ex) {Slog.w(TAG, "Dropping shortcut key combination because "+ "the activity to which it is registered was not found: "+ "SEARCH+" + KeyEvent.keyCodeToString(keyCode), ex);}} else {Slog.i(TAG, "Dropping unregistered shortcut key combination: "+ "SEARCH+" + KeyEvent.keyCodeToString(keyCode));}}return -1;}}// Invoke shortcuts using Meta.if (down && repeatCount == 0 && !keyguardOn&& (metaState & KeyEvent.META_META_ON) != 0) {final KeyCharacterMap kcm = event.getKeyCharacterMap();if (kcm.isPrintingKey(keyCode)) {Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode,metaState & ~(KeyEvent.META_META_ON| KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON));if (shortcutIntent != null) {shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);try {mContext.startActivity(shortcutIntent);} catch (ActivityNotFoundException ex) {Slog.w(TAG, "Dropping shortcut key combination because "+ "the activity to which it is registered was not found: "+ "META+" + KeyEvent.keyCodeToString(keyCode), ex);}return -1;}}}// Handle application launch keys.if (down && repeatCount == 0 && !keyguardOn) {String category = sApplicationLaunchKeyCategories.get(keyCode);if (category != null) {Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);try {mContext.startActivity(intent);} catch (ActivityNotFoundException ex) {Slog.w(TAG, "Dropping application launch key because "+ "the activity to which it is registered was not found: "+ "keyCode=" + keyCode + ", category=" + category, ex);}return -1;}}// Display task switcher for ALT-TAB or Meta-TAB.if (down && repeatCount == 0 && keyCode == KeyEvent.KEYCODE_TAB) {if (mRecentAppsDialogHeldModifiers == 0 && !keyguardOn) {final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK;if (KeyEvent.metaStateHasModifiers(shiftlessModifiers, KeyEvent.META_ALT_ON)|| KeyEvent.metaStateHasModifiers(shiftlessModifiers, KeyEvent.META_META_ON)) {mRecentAppsDialogHeldModifiers = shiftlessModifiers;showOrHideRecentAppsDialog(RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW);return -1;}}} else if (!down && mRecentAppsDialogHeldModifiers != 0&& (metaState & mRecentAppsDialogHeldModifiers) == 0) {mRecentAppsDialogHeldModifiers = 0;showOrHideRecentAppsDialog(keyguardOn ? RECENT_APPS_BEHAVIOR_DISMISS :RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH);}// Handle keyboard language switching.if (down && repeatCount == 0&& (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH|| (keyCode == KeyEvent.KEYCODE_SPACE&& (metaState & KeyEvent.META_CTRL_MASK) != 0))) {int direction = (metaState & KeyEvent.META_SHIFT_MASK) != 0 ? -1 : 1;mWindowManagerFuncs.switchKeyboardLayout(event.getDeviceId(), direction);return -1;}if (mLanguageSwitchKeyPressed && !down&& (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH|| keyCode == KeyEvent.KEYCODE_SPACE)) {mLanguageSwitchKeyPressed = false;return -1;}// Let the application handle the key.return 0;}



这篇关于Android4.1中会被系统拦截的InputEent的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

C#实现系统信息监控与获取功能

《C#实现系统信息监控与获取功能》在C#开发的众多应用场景中,获取系统信息以及监控用户操作有着广泛的用途,比如在系统性能优化工具中,需要实时读取CPU、GPU资源信息,本文将详细介绍如何使用C#来实现... 目录前言一、C# 监控键盘1. 原理与实现思路2. 代码实现二、读取 CPU、GPU 资源信息1.

在C#中获取端口号与系统信息的高效实践

《在C#中获取端口号与系统信息的高效实践》在现代软件开发中,尤其是系统管理、运维、监控和性能优化等场景中,了解计算机硬件和网络的状态至关重要,C#作为一种广泛应用的编程语言,提供了丰富的API来帮助开... 目录引言1. 获取端口号信息1.1 获取活动的 TCP 和 UDP 连接说明:应用场景:2. 获取硬

JAVA系统中Spring Boot应用程序的配置文件application.yml使用详解

《JAVA系统中SpringBoot应用程序的配置文件application.yml使用详解》:本文主要介绍JAVA系统中SpringBoot应用程序的配置文件application.yml的... 目录文件路径文件内容解释1. Server 配置2. Spring 配置3. Logging 配置4. Ma

2.1/5.1和7.1声道系统有什么区别? 音频声道的专业知识科普

《2.1/5.1和7.1声道系统有什么区别?音频声道的专业知识科普》当设置环绕声系统时,会遇到2.1、5.1、7.1、7.1.2、9.1等数字,当一遍又一遍地看到它们时,可能想知道它们是什... 想要把智能电视自带的音响升级成专业级的家庭影院系统吗?那么你将面临一个重要的选择——使用 2.1、5.1 还是

高效管理你的Linux系统: Debian操作系统常用命令指南

《高效管理你的Linux系统:Debian操作系统常用命令指南》在Debian操作系统中,了解和掌握常用命令对于提高工作效率和系统管理至关重要,本文将详细介绍Debian的常用命令,帮助读者更好地使... Debian是一个流行的linux发行版,它以其稳定性、强大的软件包管理和丰富的社区资源而闻名。在使用

Ubuntu系统怎么安装Warp? 新一代AI 终端神器安装使用方法

《Ubuntu系统怎么安装Warp?新一代AI终端神器安装使用方法》Warp是一款使用Rust开发的现代化AI终端工具,该怎么再Ubuntu系统中安装使用呢?下面我们就来看看详细教程... Warp Terminal 是一款使用 Rust 开发的现代化「AI 终端」工具。最初它只支持 MACOS,但在 20

windows系统下shutdown重启关机命令超详细教程

《windows系统下shutdown重启关机命令超详细教程》shutdown命令是一个强大的工具,允许你通过命令行快速完成关机、重启或注销操作,本文将为你详细解析shutdown命令的使用方法,并提... 目录一、shutdown 命令简介二、shutdown 命令的基本用法三、远程关机与重启四、实际应用

Debian如何查看系统版本? 7种轻松查看Debian版本信息的实用方法

《Debian如何查看系统版本?7种轻松查看Debian版本信息的实用方法》Debian是一个广泛使用的Linux发行版,用户有时需要查看其版本信息以进行系统管理、故障排除或兼容性检查,在Debia... 作为最受欢迎的 linux 发行版之一,Debian 的版本信息在日常使用和系统维护中起着至关重要的作

什么是cron? Linux系统下Cron定时任务使用指南

《什么是cron?Linux系统下Cron定时任务使用指南》在日常的Linux系统管理和维护中,定时执行任务是非常常见的需求,你可能需要每天执行备份任务、清理系统日志或运行特定的脚本,而不想每天... 在管理 linux 服务器的过程中,总有一些任务需要我们定期或重复执行。就比如备份任务,通常会选在服务器资

TP-LINK/水星和hasivo交换机怎么选? 三款网管交换机系统功能对比

《TP-LINK/水星和hasivo交换机怎么选?三款网管交换机系统功能对比》今天选了三款都是”8+1″的2.5G网管交换机,分别是TP-LINK水星和hasivo交换机,该怎么选呢?这些交换机功... TP-LINK、水星和hasivo这三台交换机都是”8+1″的2.5G网管交换机,我手里的China编程has