androidkotlinkotlin-coroutinescountdowntimerandroid-handler

How to Implement or Handle the CountDownTimer using Kotlin Coroutines


I build an android app Countdown Timer using Kotlin. When I start the timer using Coroutines it throws an error as follows.

Need your help that:

Error Text:

java.lang.RuntimeException: Can't create handler inside thread Thread[DefaultDispatcher-worker-1,5,main] that has not called Looper.prepare()

Code:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btnStartPause.setOnClickListener {
            if (isRunning) {
                pauseTimer()
            } else {
                val time = edtTxtTimer.text.toString().trim()
                timeInMilliSeconds = time.toLong() * 60000L // 1m = 60,000ms
               
                CoroutineScope(Dispatchers.Default).launch {
                        startTimer(timeInMilliSeconds)
                }
            }
        }
    }
    
    ////////////////////////////////////////////////////
    ////////////////////////////////////////////////////

    private fun startTimer(time_in_milli_second: Long) {
        countdown_timer = object : CountDownTimer(time_in_milli_second, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                timeInMilliSeconds = millisUntilFinished
                updateUI()
            }

            override fun onFinish() {
                btnStartPause.text = "Start"
                loadConfeti()
            }
        }
        countdown_timer.start()

        isRunning = true
        btnStartPause.text = "Pause"
        btnReset.visibility = View.GONE
    }

Solution

  • There are two ways to implement CountDownTimer to resolve the above error:

    First Way

    Second Way