I would like to detect when was the last time the user interacted with the screen. I'm not interested in doing any malware/spyware stuff, just need to calculate how much time has elapsed since the last time the user tapped on the screen.
The goal is to achieve a functionality similar to that of a keyguard.
I've been doing some research and following some to Q&A on the site (such as Android Best Way to Detect and Handle User INACTIVITY, Android: Detect General Use by User among others) but when it comes to detect user interaction in android I haven't found what I need.
Thanks in advance.
After some more research and testing I've managed to rise with a solution.
What I did was to create a background service in which I get an instance of the WindowManager and add a zero sized view that get's notified of user touches outside of it... but as the view has zero size it can get called every time. For that we may check https://developer.android.com/reference/android/view/WindowManager.LayoutParams.html
The InactivityService.java class detects every time the user taps the screen and write it to the preferences so it can be displayed or employed later in other components of the app. It's valid to notice that we can broadcast the time, or pass it to our app object or whatever other solution suits or needs.
We should add the following permission to the manifest:
Also valid to mention that this method, combined with getting the running tasks with ActivityManager is a very effective way to determine if the user is interacting with the handset.
I managed to improve the solution of Junior Buckeridge such that the SYSTEM_ALERT_WINDOW permission is not required anymore. The idea is the same: we add a view that receives all onpress events. But my solution just adds this view in the onCreate of the activity and uses the WindowManager.LayoutParams.TYPE_APPLICATION instead of WindowManager.LayoutParams.TYPE_SYSTEM_ALERT when creating the LayoutParams.
So I am using @Junior Buckeridge solution, but actually I got a crash, since we are not allowed to draw over the application window. (Bad token exception)
What really helped me:
in your Activity:
and also add the:
source: Android: Unable to add window. Permission denied for this window type (Anam Ansari's answer)
You could use an AccessibilityService, which would allow you to listen for click, scroll, and other interaction events. One limitation is that it doesn't report raw touch events unless they trigger actions.