Skip to content

Instantly share code, notes, and snippets.

@Struka9

Struka9/BackgroundService.kt Secret

Created Aug 13, 2019
Embed
What would you like to do?
// MyStartedService.kt
class MyStartedService: Service() {
private fun doWork(startId: Int, url: String) {
// Let's fetch something using the url
stopSelf(startId)
}
override fun (intent: Intent?, flags: Int, startId: Int): Int {
intent?.getStringExtra("EXTRA_URL")?.let {
doWork(startId, it)
}
return START_REDELIVER_INTENT
}
override fun onBind(intent: Intent): IBinder? {
// If we don't need to support binding for the service we return a null IBinder
return null
}
}
// MyActivity.kt
class MyActivity: AppCompatActivity() {
// ...
lateinit var fetchBt: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.my_activity)
// ... Complete the activity setup
fetchBt.setOnClickListener {
val intent = Intent(this@MyActivity, MyStartedService::class.java).apply {
putExtra("EXTRA_URL", myUrl)
}
startService(intent)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment