TL;DR
The idea of “hooking” the Window.Callback from a global Application callback can work, but it is fragile, hard to maintain, and easy to break (especially when other libraries or the framework itself replace the callback).
For most apps a much simpler and safer solution is to:
- Leverage the built‑in
Activity.onUserInteraction() (or a small base‑activity that forwards the call).
- Optionally add a
ViewTreeObserver.OnTouchListener at the root view for non‑activity UI (e.g., dialogs, fragments).
- Combine it with
ProcessLifecycleOwner to know when the app goes to the background/foreground.
Below you’ll find a detailed critique of the posted approach, the pitfalls you’ll likely hit, and a set of recommended patterns (with code snippets) that are easier to reason about and less error‑prone.
1. What the posted code does (and why it looks attractive)
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
if (activity is AppCompatActivity) {
activity.window?.callback = object : Window.Callback by activity.window.callback {
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_DOWN ||
event.action == MotionEvent.ACTION_UP) {
UserSessionManager.updateLastInteraction()
}
return activity.window.callback.dispatchTouchEvent(event)
}
}
}
}
// … other empty callbacks …
})
- Goal – Intercept every touch‑down/up that reaches the window and update a “last‑interaction” timestamp.
- Why it seems nice – One‑liner in
Application, no need to touch each Activity or Fragment.
2. Why this is not a great long‑term approach
| Issue | Explanation | Real‑world impact |
|---|
| Callback hijacking | You replace Window.Callback with a proxy that forwards to the original callback. If any other component (e.g., a library, a custom Dialog, a Toolbar, or even the system) later sets its own callback, your proxy is overwritten and you lose the touch‑tracking. | Interaction timestamps stop updating silently. |
| Multiple activities | Each onActivityCreated creates a new proxy. If the same activity is recreated (e.g., configuration change) you end up wrapping the already‑wrapped callback → a chain of proxies that grows indefinitely. | Memory leak & stack‑overflow‑like recursion when dispatching events. |
| Non‑touch input | Only ACTION_DOWN/UP are considered. Keyboard events, trackball, stylus hover, accessibility gestures, and even onUserInteraction() (which also fires on key events) are ignored. | “User is active” is under‑reported for many use‑cases (e.g., TV remote, external keyboard). |
| Dialog‑level windows | Dialogs create their own Window (often a PhoneWindow). Those windows are not covered by the activity’s window.callback. | Touches inside a dialog won’t update the timestamp. |
| Lifecycle edge‑cases | When an activity is finishing, the proxy remains attached to the window until the window is destroyed. If you forget to restore the original callback, you may keep a reference to the activity (leak). | Memory leak, especially on low‑memory devices. |
| Testing & readability | The logic lives in a global place that is far from the UI code. New developers will have a hard time tracing why a touch does (or does not) update the session. | Higher maintenance cost. |
| Performance | The proxy adds an extra method call for every dispatched touch event (including the many that never reach the UI, like system gestures). The overhead is tiny but unnecessary. | Negligible on modern devices, but still avoidable. |
3. Safer, more idiomatic alternatives
3.1. Use Activity.onUserInteraction()
Activity already provides a callback that is invoked for any user interaction (touch, key, trackball, etc.) before the event is dispatched to the view hierarchy.
open class BaseActivity : AppCompatActivity() {
override fun onUserInteraction() {
super.onUserInteraction()
UserSessionManager.updateLastInteraction()
}
}
-
Pros
- One line per activity (or a single base class).
- Handles all input types automatically.
- No proxy, no risk of overwriting callbacks.
-
Cons
- You need to make every activity inherit from
BaseActivity (or use a Kotlin interface with default implementation + by delegation).
Tip: If you cannot change the inheritance hierarchy (e.g., you already extend a third‑party activity), you can create a LifecycleObserver that registers a ViewTreeObserver.OnTouchListener on the activity’s decor view in onResume and removes it in onPause. This still avoids the Window.Callback hack.
3.2. Global ViewTreeObserver on the decor view
class InteractionObserver(
private val activity: Activity,
private val onInteraction: () -> Unit
) : LifecycleObserver {
private val listener = ViewTreeObserver.OnTouchListener { _, event ->
if (event.action == MotionEvent.ACTION_DOWN ||
event.action == MotionEvent.ACTION_UP) {
onInteraction()
}
false // let the event continue
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun attach() {
activity.window.decorView.viewTreeObserver?.addOnTouchListener(listener)
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun detach() {
activity.window.decorView.viewTreeObserver?.removeOnTouchListener(listener)
}
}
- Register it in a base activity or via
ActivityLifecycleCallbacks:
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
if (activity is AppCompatActivity) {
ProcessLifecycleOwner.get().lifecycle.addObserver(
InteractionObserver(activity) {
UserSessionManager.updateLastInteraction()
}
)
}
}
// … other callbacks …
})
}
}
-
Pros
- Works for dialogs that are attached to the same window (because they share the decor view).
- No need to replace
Window.Callback.
-
Cons
- Still only catches touch events; you’d need a separate
OnKeyListener for keyboards.
3.3. Combine with ProcessLifecycleOwner for app‑wide idle detection
If you want to know when the whole app goes idle (e.g., to log out after X minutes of inactivity), you can combine the per‑interaction updates with a LifecycleObserver that watches the process lifecycle:
class InactivityWatcher(
private val timeoutMillis: Long,
private val onTimeout: () -> Unit
) : LifecycleObserver {
private val handler = Handler(Looper.getMainLooper())
private val timeoutRunnable = Runnable { onTimeout() }
init {
// Start the timer when the app comes to foreground
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onAppForegrounded() {
resetTimer()
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onAppBackgrounded() {
handler.removeCallbacks(timeoutRunnable)
}
fun resetTimer() {
handler.removeCallbacks(timeoutRunnable)
handler.postDelayed(timeoutRunnable, timeout