Skip to main content

How to create a timer in android app

inside MainActivity.kt

class MainActivity: AppCompatActivity(){
    private var countDownTimer:CountDownTimer? = null // variable for timer which will be initilized later
    private var timerDuration: Long = 60000 // the duration of timer in milliseconds
    private var pauseOffSet: Long = 0

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

        tvTimer.text = "${timerDuration/100}.toString()"
       
        btnStart.setOnClickListner{
            startTimer(pauseOffSet)
        }
       
        btnPause.setOnClickListner{
            pauseTimer()
        }
       
        btnStop.setOnClickListener{
            resetTimer()
        }
    }

// function is used to start the timer of 60 sec
    private fun startTimer(pauseoffSetL: Long){
        countDownTimer = object : CountDownTimer(timerDuration - pauseOffsetL, 1000 ){
            override fun onTick(millisUntilFinished:Long){
                pauseOffSet = timeDuration - millisUntilFinished
                tvTimer.text = (millisUntilFinished/1000).toString() // current progress is set TV

            }
            override fun onFinish(){
                Toast.makeText(this@MainActivity, "Timer is finished ", Toast.LENGTH_LONG).show()
            }

        }.start()

    }
// function to pause the count timer
    private fun pauseTimer(){
        if(countdownTimer != null){
            countDownTiemr!!.cancel()
        }
    }
// function is used to reset the count down timer
    private fun resetTimer(){
        if(countDownTimer != null){
            countDownTimer!!.cancel()
            tvTimer.text = ${(timerDuration/1000).toString()}
            countDownTimer = null
            paseOffSet = 0
        }
    }

}

Comments