androidkotlinandroid-fragmentsservicecommunication

Communication between Service and fragment


How can we communicate/pass data betweeen service and fragment

I am trying to make a service and i am doing some action in that and i want to update my fragment ui state according to that action which is performed through service but i don't know how to do it


Solution

  • There are many ways you can do that

    1. First and easy way is you can directly get service variable in fragment like this :

          lateinit var sessionService: SessionService
          var isBound = false
      
          val connection = object : ServiceConnection {     
          override fun onServiceConnected(className: ComponentName, service: IBinder){
      
          val binder = service as SessionService.SessionBinder
          sessionService = binder.getService()
          sessionService.exoPlayer = activity.exoPlayer
          isBound = true
      
          if (!mViewModel.prefManager.sessionCompleted) {
              collectServiceStates()
              collectServiceProgress()
          }
      }
      
      override fun onServiceDisconnected(arg0: ComponentName) {
          isBound = false
      }
      }
      
      val progress = sessionService.progress
      
    2. Next you can use stateflow or livedata in service and collect/observe it in fragment like this :

    Service file :

    fun stopSession(){
            **curretState.value = SessionState.Stopped**
            resetValues()
            countDownTimer.cancel()
            if (isPlaying) {
                pauseAudio()
            }
        } 
    

    Fragment file :

    fun collectServiceStates(){
            viewLifecycleOwner.lifecycleScope.launch(Dispatchers.Main) {
                sessionService.curretState.collectLatest {
                    when(it){
                        SessionState.Paused -> {
                            pauseSession()
                        }
                        SessionState.Started -> {
                            startSession()
                        }
                        SessionState.Stopped -> {
                            stopSession()
                        }
                        SessionState.Completed -> {
                            updateMainViews(true)
                            mViewModel.prefManager.sessionCompleted=true
                        }
    
                        SessionState.Resumed -> {
                            resumeSession()
                        }
                        SessionState.Idle -> {
    
                        }
                    }
                }
            }
        }
    
    1. One other way is you can use Local broadcast receiver to communicate between service and fragment