Skip to content

Instantly share code, notes, and snippets.

@Miha-x64 Miha-x64/BoundService.kt
Last active Dec 5, 2018

What would you like to do?
Boilerplate for bound services (may become a part of later
package net.aquadc.flawless.service
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Binder
import android.os.IBinder
* An Android service which provides a plain, Android-independent service.
abstract class BoundService<T> : Service() {
* Actual service which should be returned to Activity.
protected abstract val actual: T
* A binder which will expose our [actual] service, when invoked as a function.
private val binder = object : Binder(), () -> Any? {
override fun invoke(): Any? = actual
final override fun onBind(intent: Intent?): IBinder? =
* Reified shortcut for [Context.bindService] with an empty [Intent] and [Context.BIND_AUTO_CREATE] flag.
inline fun <reified T : BoundService<*>> Context.bindService(connection: ServiceConnection) {
check(bindService(Intent(this,, connection, Context.BIND_AUTO_CREATE))
* @return actual service provided by a [BoundService] instance
@Suppress("UNCHECKED_CAST") // I don't mind, really
fun <T> IBinder.getActual(): T =
(this as () -> Any?)() as T
class SomeServiceHost : BoundService<SomeService>() {
override val actual = SomeService()
// and do whatever you need
class SomeUi : Activity or Fragment, ServiceConnection {
override fun onStart() {
override fun onStop() {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
override fun onServiceDisconnected(name: ComponentName) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.