1

I am downloading a file using a foreground service, but when I pause the download I want to stop the service, so I did as following

starting the service

val intent = Intent(context, IdmService::class.java)
context.startService(intent)
context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)

stopping the service

context.unbindService(serviceConnection)
context.stopService(Intent(context, IdmService::class.java))

notification update

private fun updateInfo(title: String, downloadedSize: Long, totalSize: Long) {
    notification.setContentTitle(title)
    notification.setContentText("${formatBytes(downloadedSize)}/${formatBytes(totalSize)}")
    notification.setContentInfo(downloadSpeed)
    notification.setProgress(100, progress, false)
    startForeground(STICKY_NOTIFICATION_ID, notification.build())
}

But when I stop the service, it takes 5 seconds to hide the notification. I tried commenting startForeground(STICKY_NOTIFICATION_ID, notification.build()) then it hide the notification instantly. I want to hide the notification instantly when I stop the service. I believe that the startForeground method is async, that's why after I killed the service is waiting for the startForeground method to complete.

Jeeva
  • 1,029
  • 3
  • 15
  • 21
  • Possibly [related](https://stackoverflow.com/questions/59526254/foreground-service-notification-always-shown-for-at-least-5-seconds) – greeble31 Jan 31 '20 at 19:39
  • 1
    I think you can fix this by avoiding the repeated calls to `startForeground()`. I mean, `startForeground()` is something you should call once, to get the service into a foreground state. IOW, `startForeground()` shouldn't be inside `updateInfo()`. You can update the notification with a simple call to `NotificationManager.notify()` (assuming it's already been associated with a running foreground service via an earlier `startForeground()`). Also, it's not clear where you're calling `updateInfo()` from. – greeble31 Jan 31 '20 at 20:40

1 Answers1

3

This seems to be related to the latest security patch:

This is expected behavior if you have the latest security patch installed - FGS notifications must be visible for at least 5 seconds

https://issuetracker.google.com/issues/147792378

Learn OpenGL ES
  • 4,759
  • 1
  • 36
  • 38