-
-
Save maciejwitowski/cb3e35e3ddee8fc9f7109d2724eb14d8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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 throughonDestroy()
We came up with this fork that handles it better (I think):
https://gist.github.com/AfzalivE/08708f9e08760cc60b9f5609320e764c
Would love to hear your thoughts.