I want to detect "user inactivity" in my Android app. To be more precise: I want to detect if the user has NOT done any interaction with my app (touching the screen, scrolling, input texts ...) for a specific time. Technically I use a timer that is reseted on each (user) interaction.
In my activity, I override the onUserInteraction method to detect interactions like scrolling, touching the screen ...
@Override
public void onUserInteraction(){
resetInactiveTimer();
}
Unfortunately, onUserInteraction is not called when the user interacts with the soft keyboard. I think the reason is, that the soft keyboard is not part of my Activity.
For the edit texts in my app I use TextWatcher and the onTextChanged method which works fine. But my app also contain a WebView that loads arbitrary web pages. Of course some web pages could contain input fields and I do not know how to detect that the user interacts with the soft keyboard to edit those text fields.
There is no direct way to detect the keyboard on Android. However, it's possible to infer the existence of the keyboard by using the InputMethodManager to determine if input views are active on the screen and if they are able to receive input from the user.
The Android system shows an on-screen keyboard—known as a soft input method—when a text field in your UI receives focus.
And a good way to do this is to use the mixin WidgetsBindingObserver on your LandingPage of the app. The mixin provides you with an enum AppLifecycleState which can have 4 values, detached, inactive, paused and resumed which depicts the current state of the app.
Still interested in this?
Your activity implements KeyEvent.Callback
, so you can override onKeyDown
:
@Override
public boolean onKeyDown (int keyCode, KeyEvent event) {
resetInactiveTimer();
return false;
}
Alternatively, (in the most common circumstance) if the key is pressed with the cursor in an EditText
or similar, you will need implement an OnKeyListener
and use the onKey
method to call resetInactiveTimer();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With