Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class ForegroundServiceLauncher(private val serviceClass: Class<out Service>) {
private var isStarting = false
private var shouldStop = false
@Synchronized
fun startService(context: Context, block: Intent.() -> Unit = {}) {
isStarting = true
shouldStop = false
ContextCompat.startForegroundService(context, Intent(context, serviceClass).apply { block() })
}
@Synchronized
fun stopService(context: Context) {
if (isStarting) {
shouldStop = true
} else {
context.stopService(Intent(context, serviceClass))
}
}
@Synchronized
fun onServiceCreated(service: Service) {
isStarting = false
if (shouldStop) {
shouldStop = false
service.stopSelf()
}
}
}
@AfzalivE

This comment has been minimized.

Copy link

@AfzalivE AfzalivE commented Nov 27, 2020

I think this works for most cases but if you call ForegroundServiceLauncher.startService() multiple times without calling ForegroundServiceLauncher.stopService(), then later try to stop the service by calling ForegroundServiceLauncher.stopService(). context.stopService() will not get called because isStarting will be true.

I think another flag for created is required, especially if the ForegroundServiceLauncher instance has to be a Kotlin object, and that isCreated flag can be set to false when the service goes through onDestroy()

We came up with this fork that handles it better (I think):
https://gist.github.com/AfzalivE/08708f9e08760cc60b9f5609320e764c

Would love to hear your thoughts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment