简体   繁体   English

为什么Android中的CountDown Timer使用处理程序?

[英]Why does CountDown Timer in Android use a Handler?

The GrepCode of count down timer shows that it uses a Handler. 倒数计时器的GrepCode显示它使用了处理程序。 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. 倒数计时器也可以在自身的UI线程中使用。

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. 碰巧的是, Handler具有用于计时目的的有用方法,例如CountDownTimer利用的postDelayed()sendMessageDelayed() 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. 它们很轻巧,因为如您所注意到的,我们不需要像TimerTimerTask这样的独立线程。

And also Countdown Timer works when used in the UI thread it self. 倒数计时器也可以在自身的UI线程中使用。

It needs a thread with an attached Looper to use Handler . 它需要一个带有Looper的线程才能使用Handler CountDownTimer is probably usually used on the main application thread, and if not that, on some separate HandlerThread . CountDownTimer可能通常在主应用程序线程上使用,如果不是,则在某些单独的HandlerThread

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. 假设您要实现一个秒表,并且希望UI每秒更改一次以显示倒数,那么onTick()处理程序可以执行此操作。 Say, you have to close the UI when the countdown timer finishes off the work, put the code in the onfinish() handler method. 假设您必须在倒数计时器完成工作后关闭UI,然后将代码放入onfinish()处理程序方法中。

You can use handler not only to communicate between threads. 您不仅可以使用处理程序在线程之间进行通信。 Handler was capability to execute some code after defined time (postDelayed function). 处理程序具有在定义的时间后执行某些代码的能力(postDelayed函数)。 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. 在android OS中,Handler是首选工具(而不是java Timer),以防万一,您需要在时间间隔后执行一些代码。 In count down timer, handler are used to tun code in one second intervals. 在倒数计时器中,处理程序用于每隔一秒调整一次代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM