Skip to content

Instantly share code, notes, and snippets.

@robertohuertasm
Created June 30, 2019 11:30
Show Gist options
  • Save robertohuertasm/d1057a46c135bd451bc682a027ebd624 to your computer and use it in GitHub Desktop.
Save robertohuertasm/d1057a46c135bd451bc682a027ebd624 to your computer and use it in GitHub Desktop.
foreground_services
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "Endless Service"
findViewById<Button>(R.id.btnStartService).let {
it.setOnClickListener {
log("START THE FOREGROUND SERVICE ON DEMAND")
actionOnService(Actions.START)
}
}
findViewById<Button>(R.id.btnStopService).let {
it.setOnClickListener {
log("STOP THE FOREGROUND SERVICE ON DEMAND")
actionOnService(Actions.STOP)
}
}
}
private fun actionOnService(action: Actions) {
if (getServiceState(this) == ServiceState.STOPPED && action == Actions.STOP) return
Intent(this, EndlessService::class.java).also {
it.action = action.name
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
log("Starting the service in >=26 Mode")
startForegroundService(it)
return
}
log("Starting the service in < 26 Mode")
startService(it)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment