Skip to content

Instantly share code, notes, and snippets.

@Miha-x64
Last active January 5, 2020 14:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Miha-x64/e792377d5a408442226923da9085f4b1 to your computer and use it in GitHub Desktop.
Save Miha-x64/e792377d5a408442226923da9085f4b1 to your computer and use it in GitHub Desktop.
Boilerplate for bound services (may become a part of http://github.com/Miha-x64/Flawless) later
package net.aquadc.flawless.service
import android.app.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.
* https://gist.github.com/Miha-x64/e792377d5a408442226923da9085f4b1
*/
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? =
binder
}
/**
* 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, T::class.java), 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() {
super.onStart()
bindService<SomeServiceHost>(this)
}
override fun onStop() {
unbindService(this)
super.onStop()
}
override fun onServiceConnected(name: ComponentName, service: IBinder) {
service.getActual<SomeService>().doWhateverYouNeed()
}
override fun onServiceDisconnected(name: ComponentName) {
doCleanUp()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment