问题
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.
回答1:
Because handlers are generally used when we are doing some user interaction using threads
True. However, "generally" != "always".
It so happens that Handler
has useful methods for timing purposes, like postDelayed()
and sendMessageDelayed()
, which CountDownTimer
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 like Timer
and TimerTask
do.
And also Countdown Timer works when used in the UI thread it self.
It needs a thread with an attached Looper
to use Handler
. CountDownTimer
is probably usually used on the main application thread, and if not that, on some separate HandlerThread
.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/19366184/why-does-countdown-timer-in-android-use-a-handler