Android: How to pause and resume a Count Down Timer?

后端 未结 8 1629
长发绾君心
长发绾君心 2020-12-02 17:20

I have developed a Count Down Timer and I am not sure how to pause and resume the timer as the textview for the timer is being clicked. Click to start then click again to pa

8条回答
  •  佛祖请我去吃肉
    2020-12-02 17:51

    Although the question doesn't include the Kotlin tag, I still think this answer belongs here due to Android tag.

    I've made a very simple library that uses the CountDownTimer internally and inspired by this answer. So far, it works as intended with my very basic use case:

    Pause the timer when the app/activity is paused, and resume when the app/activity resumes.

    Usage:

    class GameActivity : Activity() {
    
        private var timer = CustomTimer(30000, 1000) // 30 seconds duration at 1 second interval
    
        override fun onCreate(savedInstanceState: Bundle?) {
            ...
            timer.onTick = { millisUntilFinished ->
                textView.text = "seconds remaining: " + millisUntilFinished / 1000
            }
            timer.onFinish = {
                TODO("do something here")
            }
        }
    
        override fun onResume() {
            super.onResume()
            timer.resume()
        }
    
        override fun onPause() {
            super.onPause()
            timer.pause()
        }
    }
    

    Source code:

    Resumable CustomTimer.kt (50 lines)

提交回复
热议问题