Forked from maciejwitowski/ForegroundServiceLauncher.kt
Last active
October 2, 2024 04:11
-
-
Save AfzalivE/08708f9e08760cc60b9f5609320e764c 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 | |
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