在应用程序的后台和使用它时显示一条关于定时器到期的消息android kotlin



有一个任务:应用程序有一个CountDownTimer。我需要确保用户在计时器到期时看到一条消息(例如,它可能是Toast消息(。计时器取决于实时性,因此即使用户不使用应用程序,计时器仍然会运行。但是,有一个条件——如果计时器恰好在用户使用fragment时结束,则会向他显示此消息。如果用户在计时器到期后输入了应用程序,则不会向他显示该消息。如何实现这一点?

还有其他方法可以做到这一点,但这将是我的方法。

  1. 启动计时器时,保持结束时间(例如将其存储在SharedPreferences中(
  2. 当你的片段出现在屏幕上,或者当你启动计时器时,使用这个持续的时间来确定是否有未来的计时器结束时间。如果有,请使用CountDownTimer或协同程序开始倒计时,取消之前可能设置的任何计时器
  3. 每当片段离开屏幕时,取消计时器

我通常会在ViewModel中保留结束时间,但为了使这个例子简单,我只在Fragment中执行。


private const TIMER_END_TIME_KEY = "timerEndTime"
class MyFragment: Fragment() {
// ...
private var countDownJob: Job? = null
// Only safe while fragment attached
private val sharedPreferences: SharedPreferences
get() = PreferenceManager.getDefaultSharedPreferences(requireContext())
private fun startNewCountDown(durationMillis: Long) {
val endTime = System.currentTimeMillis() + durationMillis
sharedPreferences.edit {
putLong(TIMER_END_TIME_KEY, endTime)
}
prepareCountDownCallback()
}
private fun cancelCountDown() {
countDownJob?.cancel()
countDownJob = null
sharedPreferences.edit {
putLong(TIMER_END_TIME_KEY, 0L)
}
}
private fun prepareCountDownCallback() {
countDownJob?.cancel()
val now = System.currentTimeMillis()
val endTime = sharedPreferences.getLong(TIMER_END_TIME_KEY, 0L)
countDownJob = if (endTime > now) {
viewLifecycleOwner.lifecycleScope.launch {
delay(endTime - now)
// Show end of timer message
}
} else {
null
}
}
override fun onPause() {
super.onPause()
countDownJob?.cancel()
countDownJob = null
}
override fun onResume() {
super.onResume()
prepareCountDownCallback()
}
}

最新更新