Why does CountDown Timer in Android use a Handler?

2019-05-25 05:21发布

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.

3条回答
The star\"
2楼-- · 2019-05-25 05:50

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.

查看更多
Lonely孤独者°
3楼-- · 2019-05-25 05:52

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.

查看更多
我想做一个坏孩纸
4楼-- · 2019-05-25 06:08

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.

查看更多
登录 后发表回答