Ответ
Для получения данных из Bound Service в Activity нужно выполнить несколько шагов:
- Создать
ServiceConnectionвActivity:
private lateinit var myService: MyBoundService
private var isBound = false
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
val binder = service as MyBoundService.LocalBinder
myService = binder.getService()
isBound = true
}
override fun onServiceDisconnected(name: ComponentName?) {
isBound = false
}
}
- Привязать сервис в
onStart()и отвязать вonStop():
override fun onStart() {
super.onStart()
Intent(this, MyBoundService::class.java).also { intent ->
bindService(intent, connection, Context.BIND_AUTO_CREATE)
}
}
override fun onStop() {
super.onStop()
if (isBound) {
unbindService(connection)
isBound = false
}
}
- Получать данные через экземпляр сервиса:
if (isBound) {
val data = myService.getData()
// Используем данные
}
Важно: не забывайте обрабатывать жизненный цикл Activity и состояние сервиса.