This is a simple example of workmanager as a forground service. The problem is that forground notification is showing even after the workmanager is stopped. I feel like the problem is related to coroutines memory leak.
@HiltWorker
class MyForegroundWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted workerParams: WorkerParameters
) : CoroutineWorker(context, workerParams) {
private lateinit var notificationBuilder: NotificationCompat.Builder
private var i: Long = 0
private val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
setForeground(createForegroundInfo())
return@withContext runCatching {
while (true) {
updateNotification(i.toString())
i += 1
}
Result.success()
}.getOrElse {
Log.d("TAG", "doWork: ${it.message}, ${i}")
Result.failure()
}
}
//..
}