To create a timer application, we have more options. For example we can use a Timer or a CountDownTimer.
A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals. Corresponding to each Timer object is a single background thread that is used to execute all of the timer’s tasks, sequentially.
CountDownTimer as simple as we see in watches and mobile phones. we can set count down time after completion of time it will stop and get 0 values. If we dig deep into the source code of the CountDownTimer, than we will see, that it uses also the Handler class.
A Handler allows us to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. When you create a new Handler, it is bound to the thread /message queue of the thread that is creating it. From that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
There are two main use cases for a Handler
- To schedule messages and runnables to be executed at some point in the future
- To enqueue an action to be performed on a different thread than your own
Our first is to create the main view. In the activity_main.xml we will have the 4 Buttons, and a TextView to show the seconds. We will align this views with ConstraintLayout.
Step 2 – The process
Basically we have only a Handler, what will be fired every second.
We have to implement the start, pause, resume and the stop events in our app. Because of this we will have many methods to handel this.
The ‘secret’ of this app is that we will use the current time to observe the timechange.
With this trick we will have an unstoppable timer.
Our Application will have 3 states
We will have this states in our Enum class and in a separated kt file.
Step 3 – MainActivity::class
The last step is to implement the code in the MainActivity::class
I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉
Have a nice a day! 🙂