Skip to content
AB

Building a Foreground Activity-Tracking Service on Android

Keep active workout timing and sensor work alive with explicit lifecycle, notification, and persistence rules.

Ashish BhakhandPublished

A live workout outlives one Compose screen. Navigation, locking the phone, or process pressure should not silently discard the session.

A foreground service can own active tracking while displaying the required persistent notification. The durable session record remains the source of truth; the service coordinates timers and sensors.

Model explicit states such as active, paused, completed, and cancelled. Persist transitions with timestamps rather than incrementing an in-memory timer every second. Elapsed time can be derived after restart.

Commands should be idempotent where possible:

Code
sealed interface WorkoutCommand {
    data class Start(val sessionId: String) : WorkoutCommand
    data object Pause : WorkoutCommand
    data object Resume : WorkoutCommand
    data object Complete : WorkoutCommand
}

Validate that commands apply to the current state. Starting the same session twice should reconcile, not create two trackers.

The notification exposes safe controls through pending intents. Account for Android's foreground-service start restrictions and declare the correct service type.

On service recreation, load the durable active session. On completion, persist first, stop sensors, update Health Connect as appropriate, and stop foreground execution.

Test the state machine separately from Android service wiring, then device-test background and process scenarios. The service provides lifetime; persistence provides recovery.

← Back to all writing