Skip to content

Instantly share code, notes, and snippets.

@maciejwitowski
Created March 23, 2019 21:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save maciejwitowski/cb3e35e3ddee8fc9f7109d2724eb14d8 to your computer and use it in GitHub Desktop.
Save maciejwitowski/cb3e35e3ddee8fc9f7109d2724eb14d8 to your computer and use it in GitHub Desktop.
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
Copy link

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