Why does CountDown Timer in Android use a Handler?

匆匆过客 提交于 2019-12-10 11:29:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!