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
)
In-Article Sponsored Content
Suggested Engineering Guides
View All Guides (22+)
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.