从 Android 中的任何片段捕获 MainActivity 中的键盘按下事件

Capture Keyboard press event in the MainActivity from any Fragment in Android

由于我的应用中的安全限制,如果不活动时间超过 2 分钟,用户将被注销。

在我的 MainActivity 中,我覆盖了 dispatchTouchEvent,每次用户与应用程序交互时都会调用它。

但是 dispatchKeyEvent 不会在用户向应用程序中输入内容时调用。因此,如果用户输入超过 2 分钟,该应用会将用户踢出。

我应该如何在不添加 TextWathcer 的情况下捕获应用程序中的任何按键事件?

dispatchKeyEvent 接受一个 KeyEvent 对象作为参数。和 From Android documentation:

Note: When handling keyboard events with the KeyEvent class and related APIs, you should expect that such keyboard events come only from a hardware keyboard. You should never rely on receiving key events for any key on a soft input method (an on-screen keyboard).

还有from here:

As soft input methods can use multiple and inventive ways of inputting text, there is no guarantee that any key press on a soft keyboard will generate a key event: this is left to the IME's discretion, and in fact sending such events is discouraged. You should never rely on receiving KeyEvents for any key on a soft input method. In particular, the default software keyboard will never send any key event to any application targetting Jelly Bean or later, and will only send events for some presses of the delete and return keys to applications targetting Ice Cream Sandwich or earlier.

为了从屏幕键盘发送按键事件,您必须将 textWatcher 添加到您的 editText。

例如:

myEditText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {

                }
            });