Search code examples
androidandroid-softkeyboardandroid-textwatcherandroid-touch-event

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


Due to a security constraint in my app, the users are logged out if there is inactivity for >2mins.

In my MainActivity I have Overided dispatchTouchEvent and it is called every time the user interacts with the app.

But dispatchKeyEvent is not called if users are typing something into the app. So the app kicks the user out if they are typing for more than 2 mins.

How should I capture any Key Press Event in my app in without adding a TextWathcer?


Solution

  • dispatchKeyEvent takes in a KeyEvent object as parameter. And 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).

    Also 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.

    In order to dispatch key events from an on-screen keyboard you, have to add textWatcher to your editText.

    For example:

    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) {
    
                    }
                });