Created
June 30, 2019 11:30
-
-
Save robertohuertasm/d1057a46c135bd451bc682a027ebd624 to your computer and use it in GitHub Desktop.
foreground_services
This file contains 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 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