Search code examples
androidkotlinrunnable

Kill Runnable process


I have a function of simple timer. That function is called in OnCreate(). When I go to another activity and come back my activity with timer is recreated and timer starts working 2x faster.

I tried to kill removeCallbacks from my Runnable but it doesn't work.

How can I kill my Runnable to prevent from stacking.

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)
    }

Solution

  • Your Runnable not killed because it runs itself in handler after remove.

    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
    }