杀死可运行进程

Kill Runnable process

我有一个简单的定时器功能。该函数在 OnCreate() 中调用。 当我去另一个 activity 并回来时,我的 activity 和计时器被重新创建并且计时器开始工作的速度提高了 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
}