Environment
Android app (Kotlin, targetSdk 33) uses WorkManager v2.8 to run periodic background uploads. Authentication uses OAuth2 token stored in EncryptedSharedPreferences. Worker obtains token at construction and reuses it across retries. Failures observed on Pixel 6 Android 13 and some OEM ROMs.
Symptoms
Background uploads scheduled via WorkManager start, but server responds 401 Unauthorized. After the device exits Doze (several hours), immediate manual retry succeeds when app in foreground. Logs show Worker used an access token that had expired; refresh token exchange not attempted inside Worker.
Observations
Worker instances are long-lived across retries; token acquisition occurs in Worker init path which executes before work constraints. Token refresh code lives in foreground auth manager and relies on active LifecycleOwner. WorkManager's ListenableWorker didn't call refresh endpoint when receiving 401; WorkManager retry count increased but kept failing with same token.
Already attempted
Added extra token validity check in Worker startWork path to call auth manager, but race persisted because auth refresh uses network constraints and requires WorkManager's own network to be available. Tried making WorkManager perform synchronous refresh using a direct HTTP call (works) but blocked under Doze due to network restrictions.
Question
What's the recommended pattern to ensure background WorkManager jobs use fresh tokens and recover from 401s under Doze without violating background execution limits?
Verified community troubleshooting
Do not capture the token at Worker creation — fetch/validate it inside doWork()/execute() and implement a synchronous refresh path there. Flow: request with current token; if you get 401, perform the refresh HTTP call using the refresh token stored in EncryptedSharedPreferences, update storage, then retry the upload once. Make sure the Worker has NetworkType.CONNECTED constraint so WorkManager runs it when network is allowed. For critical uploads use ExpeditedWorkRequest with a foreground service. Rollback by reverting changes if you see regressions, but keep token refresh logic server-safe (rate-limited).
Incident analysis
Most likely causes
Summary
Suggested Fixes
Continue troubleshooting
Related troubles
Matched from the title, description and tags