How to create a simple countdown timer in Kotlin?

后端 未结 5 370
迷失自我
迷失自我 2020-12-28 14:17

I know how to create a simple countdown timer in Java. But I\'d like to create this one in Kotlin.

package android.os;

new CountDownTimer(20000, 1000) {
             


        
5条回答
  •  旧巷少年郎
    2020-12-28 15:07

    I've solved my problem with timer in Kotlin like this:

    class Timer {
    
        private val job = SupervisorJob()
        private val scope = CoroutineScope(Dispatchers.Default + job)
    
        private fun startCoroutineTimer(delayMillis: Long = 0, repeatMillis: Long = 0, action: () -> Unit) = scope.launch(Dispatchers.IO) {
            delay(delayMillis)
            if (repeatMillis > 0) {
                while (true) {
                    action()
                    delay(repeatMillis)
                }
            } else {
                action()
            }
        }
    
        private val timer: Job = startCoroutineTimer(delayMillis = 0, repeatMillis = 20000) {
            Log.d(TAG, "Background - tick")
            doSomethingBackground()
            scope.launch(Dispatchers.Main) {
                Log.d(TAG, "Main thread - tick")
                doSomethingMainThread()
            }
        }
    
        fun startTimer() {
            timer.start()
        }
    
        fun cancelTimer() {
            timer.cancel()
        }
    //...
    }
    

    I've used Coroutines for a timer.

提交回复
热议问题