如何 stop/cancel activity 中的任务?.runOnUiThread Android 中的任务?

How to stop/cancel a task in activity?.runOnUiThread in Android?

我已经使用计时器 class 在 Kotlin 中为 Android 应用程序创建了 StopWatch 函数。我正在使用 activity?.runOnUiThread 在应用栏(而不是视图)中显示时间。有什么简单的方法可以停止计时器并将其设置回0。是否需要多线程?

这是我的函数:

   private fun stopwatch(isCanceled: Boolean) {
    val timer = Timer()

    val tt: TimerTask = object : TimerTask() {
        override fun run() {
            num += 1000L
            val runnable = Runnable { setModeTitle(getString(R.string.chipper_title) + TimerUtil.timerDisplay(num)) }
            activity?.runOnUiThread(runnable)
        }
    }

    timer.schedule(tt, 0L, 1000)

    if (isCanceled) {
       //what to implement here, if possible?
    }
}

您需要存储生成的 TimerTask 对象,然后在其上调用 cancel()。类似于:

private var tt: TimerTask? = null

private fun stopwatch() {
    val timer = Timer()

    tt = object : TimerTask() {
        override fun run() {
            num += 1000L
            val runnable = Runnable { setModeTitle(getString(R.string.chipper_title) + TimerUtil.timerDisplay(num)) }
            activity?.runOnUiThread(runnable)
        }
    }

    timer.schedule(tt, 0L, 1000)
}

private fun cancelStopwatch() {
    tt?.cancel()
}

只要确保不要调用 stopwatch() 两次,而不先取消已经 运行 的秒表。