Android 计时器没有取消
这个问题的其他例子都不能解决我的问题。我有一个片段出现在事务序列的末尾。它意味着在应用程序中包含的Android 计时器没有取消,android,kotlin,timer,timertask,Android,Kotlin,Timer,Timertask,这个问题的其他例子都不能解决我的问题。我有一个片段出现在事务序列的末尾。它意味着在应用程序中包含的计时器完成时关闭应用程序: var terminalTimer: Timer? = null class TerminalFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCre
计时器完成时关闭应用程序:
var terminalTimer: Timer? = null
class TerminalFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_terminal, container, false)
}
override fun onStart() {
super.onStart()
initUi()
startCountDown()
}
override fun onStop() {
super.onStop()
AppLog.i(TAG, "onStop()")
stopCountDown()
}
private fun startCountDown() {
if (terminalTimer == null) {
terminalTimer = Timer()
terminalTimer!!.schedule(object : TimerTask() {
override fun run() {
AppLog.i(TAG, "Terminal countdown finished")
{
activity?.finish()
}
}, 5000)
}
}
private fun stopCountDown() {
AppLog.i(TAG, "stopCountDown()")
terminalTimer?.cancel()
terminalTimer?.purge()
terminalTimer = null
}
private fun returnToStart() {
AppLog.i(TAG, "returnToStart()")
(context as MainActivity).restartFlow() // calls popBackStackImmediate() for every fragment in the backstack, returning user to the beginning of their flow
}
companion object {
@JvmStatic
fun newInstance(terminalType: String, amountLoaded: Double) =
TerminalFragment().apply {
arguments = Bundle().apply {
}
}
}
}
stopCountDown()
在片段被导航离开时被调用,但有时它会以某种方式存活下来,并从另一个片段关闭应用程序。通过使用日志,我还发现这个计时器有时似乎有两个实例。如何确保此倒计时在此片段之外从未处于活动状态,并在片段的onStop()中取消/销毁?计时器的取消方法不会干扰任何活动运行的任务,但会干扰计划的任务。因此,如果任务当前正在运行,调用cancel
不会影响它。任务是否被视为在延迟期间运行?因为这通常是在我调用.cancel()时发生的。如何从非UI线程调用finish()
,而不会崩溃?我自己从来没有试过,但这很令人惊讶。IMHO,你最初的倒计时方法更有意义。