将信息从服务传递给片段

huangapple go评论71阅读模式
英文:

Transfer information from service to fragment

问题

我有一个片段(fragment)和一个被片段调用的服务(service)。
片段中包含一个仪表(gauge),而服务则使用设备的麦克风来测量声音。我希望仪表能够反映出声音的变化。
我想知道是否有办法将服务中测得的声音值传递到片段中?
我尝试过通过可序列化对象将片段中的仪表对象传递到服务中,但由于该仪表来自自定义库,无法进行序列化或者打包(parcelize)。
我还尝试过创建一个仅带有整数属性的自定义类,将该对象从片段传递到服务,希望在服务中更新整数属性会同时更新片段中的整数,但结果并不如预期。
我希望这种更新能够在每秒测量的过程中都实时发生,因此在服务的 OnDestroy 事件中发送信息对我并不起作用。

您对我有什么建议吗?谢谢。

英文:

I have a fragment and a service that is called by the fragment.
The fragment contains a gauge, and the service uses a device's microphone to meausure sound. I would like the gauge to reflect the sound.
Is there a way for me to transfer the sound value from the service to the fragment?
I have tried to send the gauge object from fragment to the service through a parcelable, but because the gauge is from a custom library, I cannot parcelize or serialize it. I have also tried to create a custom class with just an int attribute, sending the object from the fragment to the service, hoping that updating the int attribute in the service would update the int in the fragment, but it didnt work out.
I want this update to be happening at each second of the measurement, so sending the information OnDestroy of the service does not work for me.

Do you have any suggestions on how I could do this? Thanks

答案1

得分: 1

与服务和片段之间的通信,您必须创建boundService
在服务中为每一秒实现TimerTask,将解决更新值的问题。
注意:我们可以在服务中使用声音值的LiveData,并在片段中注册其观察者,因此无论何时计时任务更新LiveData对象中的值,都将在片段中反映出来。

英文:

For Communication between service and fragment, you have to create boundService.
Implementing TimerTask in service for each second will solve problem of updating value.
Note: we can use liveData of sound value in service and register its observer in fragment so whenever timertask update value in livedata object it will reflect in fragment.

huangapple
  • 本文由 发表于 2020年9月27日 13:46:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64085233.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定