Skip to content
AB

Reliable Background Health Sync with WorkManager

Schedule constrained, resumable Android work while keeping foreground refresh and worker execution on one coordinator.

Ashish BhakhandPublished

WorkManager provides durable scheduling, not exact timing. The system may delay work to protect battery and combine jobs.

Use unique work so repeated scheduling does not create competing syncs:

Code
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
    "health-sync",
    ExistingPeriodicWorkPolicy.UPDATE,
    request,
)

Set network constraints only for stages that upload. Health Connect-to-Room import can sometimes succeed offline, while remote synchronization waits.

Both the worker and foreground refresh should call the same HealthSyncCoordinator. The coordinator serializes stages and persists progress; the worker only supplies execution context.

Return Result.retry() for temporary infrastructure failures with bounded WorkManager backoff. Validation, revoked permission, and unsupported devices are not retryable in the same way.

Workers can stop. Check cancellation between bounded pages and commit progress after each safe unit. Avoid one enormous transaction for months of history.

Observe last successful import and upload rather than whether WorkManager happened to start. Foreground launch remains a catch-up path because periodic work is intentionally inexact.

Test unique scheduling, constraints, retries, cancellation, and resumption with a test driver. Background execution becomes reliable through durable work, not precise schedules.

← Back to all writing