You're on the right track — intercepting window callbacks is a common way to catch user interaction without modifying every Activity — but your snippet has a critical bug and a few other concerns. Summary and fixes below.
Problems in your snippet
- Infinite recursion / StackOverflow: you set activity.window.callback to your wrapper, then call activity.window.callback.dispatchTouchEvent(...) inside the wrapper. That calls the wrapper again. You must save the original callback reference and call that.
- You only handle touch ACTION_DOWN/ACTION_UP. You probably want ACTION_MOVE and other input types (key events, generic motion) too.
- Possible double-wrapping: if you run this more than once or the callback is already wrapped, you may wrap again.
- Performance/persistence: if updateLastInteraction() writes to disk on every touch, it will be expensive. Debounce or keep in-memory and persist occasionally.
- Dialogs/other windows: dialog windows or system windows may not be covered by the Activity window callback.
- Soft keyboard IME input: not all soft-keyboard input produces KeyEvents to the Activity; typing may not always be captured.
A corrected, more robust approach (Kotlin)
- Capture original callback
- Avoid double-wrapping
- Track touch, key and generic motion events
- Use actionMasked for multi-touch
Example:
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
// Optionally: only do this in the main process
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
val window = activity.window ?: return
val original = window.callback ?: return
// Avoid double-wrapping
if (original is InteractionTrackingWindowCallback) return
window.callback = InteractionTrackingWindowCallback(original)
}
override fun onActivityStarted(activity: Activity) {}
override fun onActivityResumed(activity: Activity) {}
override fun onActivityPaused(activity: Activity) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
override fun onActivityDestroyed(activity: Activity) {}
})
}
private class InteractionTrackingWindowCallback(
private val original: Window.Callback
) : Window.Callback by original {
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN,
MotionEvent.ACTION_UP,
MotionEvent.ACTION_MOVE,
MotionEvent.ACTION_CANCEL -> UserSessionManager.updateLastInteraction()
}
return original.dispatchTouchEvent(event)
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (event.action == KeyEvent.ACTION_DOWN) {
UserSessionManager.updateLastInteraction()
}
return original.dispatchKeyEvent(event)
}
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
// mouse/joystick, etc.
UserSessionManager.updateLastInteraction()
return original.dispatchGenericMotionEvent(event)
}
// Other methods are delegated to original via "by original"
}
}
Alternatives & recommendations
- If you control all Activities, the simplest approach is a BaseActivity that overrides onUserInteraction():
open class BaseActivity : AppCompatActivity() {
override fun onUserInteraction() {
super.onUserInteraction()
UserSessionManager.updateLastInteraction()
}
}
onUserInteraction() is called for key/touch/trackball events and is less intrusive than wrapping callbacks.
-
Use ProcessLifecycleOwner (or Application.ActivityLifecycleCallbacks) to detect app foreground/background. When coming to foreground, compare current time vs lastInteraction to decide whether to lock the app.
-
Make updateLastInteraction cheap: keep lastInteraction in-memory and persist to SharedPreferences or DB with debounce (e.g., persist at most once per N seconds or on pause) to avoid doing IO on every touch.
-
Test edge cases: dialogs, popups, WebViews, IME input. You may want to add TextWatchers for EditTexts if typing must count (rarely necessary because the touch to focus is usually counted).
Conclusion
- Hooking Window.Callback is a valid approach when you can't change every Activity, but you must capture the original callback (avoid recursion), handle more event types, avoid double-wrapping, and ensure updateLastInteraction is cheap/ debounced.
- If you can modify Activities, overriding onUserInteraction() in a shared base Activity is simpler and more robust.
If you want, I can:
- give a debounced UserSessionManager implementation (in-memory + periodic persistence),
- show how to combine this with ProcessLifecycleOwner to implement a session timeout/lock screen flow. Which would you prefer?