当调用showSnackBarInfo()
方法时,函数startTimer
在lambda中多次运行:
private var timer: CountDownTimer? = null
private val handler = Handler(Looper.getMainLooper())
private val timerAction = Runnable { showSnackBarInfo() }
var timerDuration = TimeUnit.SECONDS.toMillis(10)
fun showSnackBarInfo() {
Log.d("some", "showSnackBarInfo")
}
fun startTimer() {
handler.removeCallbacks(timerAction)
handler.postDelayed(timerAction, timerDuration)
}
fun cancelTimer() = handler.removeCallbacks(timerAction)
解决了我的TimerTask问题:
private var timerDuration = TimeUnit.MINUTES.toMillis(1)
private var timer: Timer? = null
fun showSnackBarInfo() {
viewContract.showInfoMessage()
}
fun startTimer() {
timer?.cancel()
timer = Timer().apply {
schedule(object : TimerTask() {
override fun run() {
showSnackBarInfo()
}
}, timerDuration)
}
}
fun cancelTimer() {
timer?.cancel()
timer?.purge()
timer = null
}