Skip to content

Instantly share code, notes, and snippets.

@bholota
Created December 31, 2018 15:44
Show Gist options
  • Save bholota/e011f1b61d0ba07ac7d7cbcda5150dfc to your computer and use it in GitHub Desktop.
Save bholota/e011f1b61d0ba07ac7d7cbcda5150dfc 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()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment