The GrepCode of count down timer shows that it uses a Handler. Is there any specific reason for using handlers? Because handlers are generally used when we are doing some user interaction using threads. But here there are no threads that I can see in Countdown Timer. And also Countdown Timer works when used in the UI thread it self.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How can I create this custom Bottom Navigation on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
You can use handler not only to communicate between threads. Handler was capability to execute some code after defined time (postDelayed function). In android OS Handler is preferred tool (instead of java Timer) to use in case then you need to execute some code after time interval. In count down timer, handler are used to tun code in one second intervals.
True. However, "generally" != "always".
It so happens that
Handler
has useful methods for timing purposes, likepostDelayed()
andsendMessageDelayed()
, whichCountDownTimer
takes advantage of. You can use those yourself as well. They are nice and lightweight because, as you note, we do not need a separate thread, the way things likeTimer
andTimerTask
do.It needs a thread with an attached
Looper
to useHandler
.CountDownTimer
is probably usually used on the main application thread, and if not that, on some separateHandlerThread
.Handlers are used to perform some task during the lifecycle of the countdown timer.
Say, you are implementing a stopwatch, and you want the UI to change every second to show the count down, onTick() handler can perform this. Say, you have to close the UI when the countdown timer finishes off the work, put the code in the onfinish() handler method.