With Jetpack's ProcessLifecycleOwner, how do you start an analytics session each time the app comes to the foreground, and why does its ON_STOP arrive late?
answer
- one lifecycle for all activities
- ProcessLifecycleOwner.get() in Application.onCreate
- ON_CREATE once, ON_DESTROY never
- delayed ON_PAUSE and ON_STOP
- rotation sends no events
basics
~20 sRegister an observer on ProcessLifecycleOwner.get().lifecycle in Application.onCreate and start the session in onStart. Its ON_PAUSE and ON_STOP are delayed after the last activity pauses and stops, so an Activity recreated for a configuration change produces no events.
solid answer
~40 s`ProcessLifecycleOwner`, from the `lifecycle-process` artifact, is a `LifecycleOwner` for the whole process: a composite of all its activities. It dispatches `ON_CREATE` once and never `ON_DESTROY`. `ON_START` and `ON_RESUME` fire as the first activity passes through them; `ON_PAUSE` and `ON_STOP` fire only after a delay once the last activity has passed through them. That delay lets an Activity be destroyed and recreated for a rotation without the app appearing to leave the foreground. So the ferry app adds a `DefaultLifecycleObserver` to `ProcessLifecycleOwner.get().lifecycle` in `Application.onCreate`, starts the analytics session in `onStart` and pauses the GPS gate check in `onStop`. It is initialised through `androidx.startup`, and it only knows about the process it runs in.
code
kotlin · 19 linesimport android.app.Application
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
class FerryApp : Application() {
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(
object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) = startSession()
override fun onStop(owner: LifecycleOwner) = pauseGateCheck()
}
)
}
private fun startSession() { /* analytics session */ }
private fun pauseGateCheck() { /* stop GPS polling */ }
}go deeper
Recall that ProcessLifecycleOwner gives the whole app one lifecycle, so you observe its ON_START and ON_STOP for foreground and background.
Explain the composite counting, ON_CREATE once and no ON_DESTROY, and where to register: Application.onCreate on the main thread.
Use the delayed ON_STOP to explain why rotation and moving between activities send no events, and avoid leaks from screen objects registered on it.
Decide which app-wide work hangs on the process lifecycle versus a screen, and account for imprecise timing and separate processes in analytics.
## One lifecycle for the whole app process Screens have their own lifecycles, but some work cares about the **app** as a whole: start an analytics session when the user brings the ferry app to the foreground, and pause the GPS boarding-gate check when the app goes to the background. The Jetpack Lifecycle library provides **`ProcessLifecycleOwner`** in the `lifecycle-process` artifact for exactly that. `ProcessLifecycleOwner.get()` returns a `LifecycleOwner` whose `lifecycle` works like any other, so the same observers and coroutine helpers apply. The library describes it as **the composite of all of your Activities**, with specific rules: | Event | When ProcessLifecycleOwner dispatches it | |---|---| | `ON_CREATE` | once, when the owner is attached at process start | | `ON_START`, `ON_RESUME` | as the **first** activity moves through them | | `ON_PAUSE`, `ON_STOP` | **with a delay** after the **last** activity has passed through them | | `ON_DESTROY` | **never** | ## Why ON_PAUSE and ON_STOP are delayed During a rotation, the only visible Activity is paused, stopped and destroyed, and a new instance is created, started and resumed. Without a delay, an app-wide observer would see the app "leave" and "return" on every configuration change, ending and restarting the analytics session. The library's documentation states that the delay is **long enough to guarantee that no events are sent** when activities are destroyed and recreated for a configuration change. In the current implementation the timeout is an internal constant of 700 milliseconds; it is not a public API, so code should not depend on the exact value. The mechanism is counting: 1. Each activity start and resume increments a counter; the first one dispatches `ON_START` or `ON_RESUME`. 2. When the resumed count reaches zero, a delayed task is posted to dispatch `ON_PAUSE` and then `ON_STOP`. 3. If another activity resumes before the delay ends, the task is cancelled and nothing is dispatched. The same counting means moving between the app's own activities produces no events either, as the next activity starts before the previous one stops. The cost is precision: the library says to use it when you **do not need millisecond accuracy**. ## Wiring the observer ```kotlin class FerryApp : Application() { override fun onCreate() { super.onCreate() ProcessLifecycleOwner.get().lifecycle.addObserver( object : DefaultLifecycleObserver { override fun onStart(owner: LifecycleOwner) = startSession() override fun onStop(owner: LifecycleOwner) = pauseGateCheck() } ) } } ``` Points worth stating in an interview: - **`onStart`/`onStop`, not `onResume`/`onPause`, mark foreground and background.** `STARTED` already means visible, so a paused activity can still be on screen, and `ON_PAUSE` alone does not mean the app has left it. - **Register on the main thread**, which `Application.onCreate` is. Like any registration, the observer is brought to the current state at once. - **Never register a screen-scoped object without removing it.** The process lifecycle outlives every Activity, and it holds observers strongly, so an Activity that adds an observer capturing itself leaks. ## Common mistakes 1. **Using `ON_RESUME` for a session start.** A session can also restart when the app's activity stays paused past the delay without ever leaving the screen. 2. **Expecting a quick `ON_STOP`.** The event comes after the delay, so a test that checks for background work straight after pressing Home fails unless it waits for the delay. 3. **Observing an Activity's lifecycle for app-wide work.** Every rotation and every navigation between activities then looks like leaving and returning. 4. **Hand-counting activities in `ActivityLifecycleCallbacks`.** That re-implements this class without its configuration-change delay, and usually gets rotation wrong. ## Initialisation and multi-process apps Since Lifecycle 2.4.0, `ProcessLifecycleOwner` is initialised by **`androidx.startup`** through `ProcessLifecycleInitializer`, declared as meta-data under the startup `InitializationProvider` that runs before `Application.onCreate`. Two consequences: - An app that removes that meta-data and initialises the component lazily gets an `IllegalStateException` whose message begins "ProcessLifecycleInitializer cannot be initialized lazily". - Per its documentation, if the app has **multiple processes**, the owner does not know about the others: activities running in a second process declared with `android:process` are not part of the main process's composite. Foreground and background as a design concern, such as what an app may rely on in each state, belongs to the app-lifecycle design material; this library only reports when the process's activities are visible.
- The analytics team sees a session end and restart on every rotation. What would cause that if ProcessLifecycleOwner suppresses it?The session is probably tied to a screen's lifecycle, such as an Activity's own `onStart`/`onStop` or an observer on the Activity's `lifecycle`, rather than to `ProcessLifecycleOwner`. Screen lifecycles do go through `ON_STOP` and `ON_START` on recreation; only the process owner's delay hides them.
- Why not use ON_DESTROY of ProcessLifecycleOwner to flush analytics on exit?It is never dispatched. The process can be killed in the background without any callback, so flushing belongs on `ON_STOP` of the process owner, when the app has left the foreground.
- ProcessLifecycleOwner dispatches ON_DESTROY when the app is closed
- Rotating the only Activity sends ON_STOP then ON_START to it
- ON_STOP arrives at the exact moment the last activity stops
- It reports the combined state of every process of the app
- Code can rely on ON_STOP arriving exactly 700 ms later
Assumes Lifecycle 2.11; lifecycle-process has initialised ProcessLifecycleOwner through androidx.startup since 2.4.0.