我具有简单计时器的功能。该函数在OnCreate()中调用。 当我转到另一项活动并返回时,将重新创建带有计时器的活动,计时器开始以2倍的速度开始工作。
我试图从Runnable中删除removeCallbacks,但是它不起作用。
如何杀死Runnable来防止其堆积。
** Desired output **
Month ProductID No_despatched No_returned Return_reason
Jan abc 10 2 Too big
Jan abc 10 3 Too small
Jan xyz 12 1 Wrong colour
答案 0 :(得分:1)
您的Runnable
未被杀死,因为它在删除后会在处理程序中运行。
var mIsStopped = false
private fun onTimerStart() {
ed.putBoolean("thread", true).apply()
mRunnable = Runnable {
seconds = sp.getLong("SECONDS", 0)
try {
if (seconds != 0L) {
startRun = true
btnStartEnd.text = getString(R.string.stop)
}
} catch (ex: Exception) {
}
val hours = seconds / 3600
val minutes = (seconds % 3600) / 60
val secs = (seconds % 60)
val time = String.format("%d:%02d:%02d", hours, minutes, secs)
txtClock.text = time
if (startRun) {
seconds++
ed.putLong("SECONDS", seconds).apply()
}
if (!mIsStopped) mHandler.postDelayed(this, 1000)
}
mHandler.postDelayed(mRunnable, 1000)
}
override fun onPause() {
mHandler.removeCallbacksAndMessages(null);
mIsStopped = true
}
override fun onResume() {
mIsStopped = false
}