How to have Android Service communicate with Activity

前端 未结 13 2134
说谎
说谎 2020-11-22 02:54

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

13条回答
  •  生来不讨喜
    2020-11-22 03:37

    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.

提交回复
热议问题