Skip to content

Instantly share code, notes, and snippets.

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

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):

Would love to hear your thoughts.

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