I\'m writing my first Android application and trying to get my head around communication between services and activities. I have a Service that will run in the background an
You may also use LiveData that works like an EventBus.
class MyService : LifecycleService() {
companion object {
val BUS = MutableLiveData()
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
val testItem : Object
// expose your data
if (BUS.hasActiveObservers()) {
BUS.postValue(testItem)
}
return START_NOT_STICKY
}
}
Then add an observer from your Activity.
MyService.BUS.observe(this, Observer {
it?.let {
// Do what you need to do here
}
})
You can read more from this blog.