Created
December 31, 2018 15:44
-
-
Save bholota/e011f1b61d0ba07ac7d7cbcda5150dfc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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