Android WorkManager Masterclass: Reliable Background Sync & Battery Optimization

Why Legacy AlarmManager & Services Are Deprecated

Modern Android versions enforce aggressive power-management restrictions (Doze Mode, App Standby Buckets). Background services started while an app is in the background are instantly terminated with ForegroundServiceStartNotAllowedException. WorkManager is the official solution for deferrable, guaranteed background execution.

1. Building a CoroutineWorker

class SyncDataWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
    override suspend fun doWork(): Result {
        return try {
            val api = RetrofitClient.instance
            val response = api.fetchLatestUpdates()
            DatabaseClient.db.articleDao().insertArticles(response)
            Result.success()
        } catch (e: Exception) {
            Result.retry()
        }
    }
}

2. Scheduling with Power & Network Constraints

val constraints = Constraints.Builder()
    .setRequiredNetworkType(NetworkType.CONNECTED)
    .setRequiresBatteryNotLow(true)
    .build()

val periodicWork = PeriodicWorkRequestBuilder(12, TimeUnit.HOURS)
    .setConstraints(constraints)
    .build()

WorkManager.getInstance(context).enqueueUniquePeriodicWork(
    "PeriodicSyncJob",
    ExistingPeriodicWorkPolicy.KEEP,
    periodicWork
)
Share this Guide Help colleagues and developers learn from this article
In-Article Sponsored Content
Mohit Kumaar
AUTHOR & FOUNDER

Mohit Kumaar

Founder & CEO of JMD WORLD with 8+ Years of industrial software engineering leadership (active since 2018). Creator and manager of 500+ production Google Play applications (proprietary & client solutions) and architect of apps.jmdworld.in. Operating from Pune & Mumbai under MSME Registration: UDYAM-MH-26-1071218 and D-U-N-SĀ® 581707246.

Previous Guide

How to Clean Up Developer Storage: Delete Gigabytes of Gradle, NPM & Docker Caches

Software Setup
Next Guide

Securing Your Developer Machine: SSH Keys, GPG Signing & Credential Storage

Developer Tools
Recommended For You Ads by Google

Comments (0)

No comments yet. Share your thoughts below!

Leave a Comment

Share your thoughts or questions. Your email address remains private.