I have a list of Master Apis which has to be synced every 24 hours. I tried periodic work requests in Job Manager with foreground notification. Everything was working fine. But I tried to run the same in Android 12, it got failed with an exception.
android.app.BackgroundServiceStartNotAllowedException: Not allowed to start service Intent
I read the documentation it says we cannot start the foreground notification service in the background. I am stuck here. Kindly suggest me some alternatives
class SyncWorker(
appContext: Context,
params: WorkerParameters,
private val masterRepo: MasterRepo,
) : CoroutineWorker(appContext, params) {
private val NOTIFICATION_ID = 96
override suspend fun doWork(): Result {
setForeground(createForegroundInfo())
masterRepo.syncMasterApis()
return Result.success()
}
private fun createForegroundInfo(): ForegroundInfo {
val title = applicationContext.getString(R.string.notif_sync_master_data)
val channel = NotificationChannel(
SYNC_MASTERDATA_FOREGOUND_SERVICE_CHANNEL_ID,
"Master Data Sync Notification",
NotificationManager.IMPORTANCE_HIGH
)
val notification =
NotificationCompat.Builder(applicationContext, SYNC_MASTERDATA_FOREGOUND_SERVICE_CHANNEL_ID)
.setForegroundServiceBehavior(FOREGROUND_SERVICE_IMMEDIATE)
.setContentTitle("Update")
.setContentText(title)
.setSmallIcon(drawable.ic_notification_status)
.setOngoing(true)
.build()
NotificationManagerCompat.from(applicationContext).createNotificationChannel(
channel
)
return ForegroundInfo(NOTIFICATION_ID, notification)
}
companion object {
fun getWorkerRequest(): PeriodicWorkRequest {
val constraints = Constraints.Builder()
.setRequiredNetworkType(CONNECTED).build()
return PeriodicWorkRequestBuilder<SyncWorker>(Duration.ofHours(24))
.setConstraints(constraints)
.build()
}
}
}