Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AfzalivE/08708f9e08760cc60b9f5609320e764c to your computer and use it in GitHub Desktop.
Save AfzalivE/08708f9e08760cc60b9f5609320e764c 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
private var isCreated = false
@Synchronized
fun startService(context: Context, block: Intent.() -> Unit = {}) {
if (!isCreated) {
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) {
isCreated = true
isStarting = false
if (shouldStop) {
shouldStop = false
service.stopSelf()
}
}
@Synchronized
fun onServiceDestroyed() {
isCreated = false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment