[英]Timer() fixedRateTimer set for 20 sec does not stop when onStop is triggered
[英]Stop a timer when Fragment onStop is called
当我试图停止我的计时器时遇到了问题。 此计时器是在 FragmentViewModel 中创建的。 如果我离开应用程序,计时器会继续运行。 我正在寻找阻止他的方法,但我无法从 Fragments onStop() 函数访问他,因为他是在 ViewModel 中创建的,它仅在 Fragments onCreate() 函数中被引用。 任何人都知道如何解决这个问题?
这就是我创建 ViewModel 的方式(里面有计时器):
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding: GameFragmentBinding = DataBindingUtil.inflate(
inflater, R.layout.game_fragment, container, false)
val application = requireNotNull(this.activity).application
val dataSource = TranslationDB.getInstance(application).translationDBDao
val viewModelFactory = GameFragmentViewModelFactory(dataSource, application)
val gameFragmentViewModel =
ViewModelProviders.of(
this, viewModelFactory).get(GameFragmentViewModel::class.java)
binding.gameFragmentViewModel = gameFragmentViewModel
提前致谢!
您可以使用 ViewModels onCleared()
回调。
要了解何时调用它(以便您可以决定它是否合适),请参阅此问题和答案When is the viewmodel onCleared called
如果您想根据生命周期事件在您的视图模型中执行某些操作,请让您的视图模型实现LifecycleObserver
接口,然后在您的视图模型中执行
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stop() {
// stop timer
}
在你的片段中,在onCreateView
你做
lifecycle.addObserver(viewmodel)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.