我有一个简单的计时器功能。该函数在OnCreate()中调用。当我去另一个活动然后回来时我会重新启动计时器并且计时器开始工作速度提高2倍。
我试图从我的Runnable中杀死removeCallbacks,但它不起作用。
如何杀死我的Runnable以防止堆叠。
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()
}
mHandler.postDelayed(this,1000)
}
mHandler.postDelayed(mRunnable,1000)
}
你的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
}