Skip to content

Instantly share code, notes, and snippets.

@Struka9
Created August 13, 2019 03:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Struka9/6fdb8b96211544ed64a35cc052f2c5af to your computer and use it in GitHub Desktop.
Save Struka9/6fdb8b96211544ed64a35cc052f2c5af to your computer and use it in GitHub Desktop.
// MyBoundService.kt
class MyBoundService: Service() {
// Extend the Binder class and expose the service instance through a method
inner class MyServiceBinder: Binder() {
fun getService() = this@MyBoundService
}
private val myBinder = MyServiceBinder()
fun doWork() {
// ...
}
override fun onBind(intent: Intent?): IBinder {
// Support binding to this service
return myBinder
}
}
// MyActivity.kt
class MyActivity: AppCompatActivity {
private val serviceConnection = object: ServiceConnection {
override fun onServiceConnected(name: ComponentName?, binder: IBinder) {
val myServiceBinder = binder as MyServiceBinder
service = myServiceBinder.getService()
}
override fun onServiceDisconnected(name: ComponentName?) {
service = null
}
}
// ...
private var service: MyBoundService? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.my_activity)
// ...
doWorkBt.setOnClickListener {
service?.doWork()
}
// ...
}
override fun onStart() {
super.onStart()
val intent = Intent(this, MyBoundService::class.java)
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
}
override fun onPause() {
super.onPause()
val intent = Intent(this, MyBoundService::class.java)
unbindService(intent)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment