CountDownTimer:“无法在未调用 Looper.prepare() 的线程内创建处理程序”
我知道以前曾问过“无法在未调用 Looper.prepare() 的线程内创建处理程序”的一般问题,但我很难理解它在这种情况下如何应用。
我正在尝试在非 UI 线程中构造一个新的 CountDownTimer,我猜这是导致此错误的原因,但我不太明白为什么需要在主线程中使用计时器。从我所看到的来看,它似乎有一个回调处理程序,需要在具有循环器的线程中运行,而非 UI 线程默认情况下没有循环器。看来我的选择是:1)让这个非 UI 线程有一个 Looper 或 2)在我的 UI 线程上创建一些奇怪的方法来构建这个计时器,这对我来说似乎都很愚蠢。有人可以帮助我理解其中的含义吗?
另外,有谁知道有任何有用的链接可以阐明 Looper 和 MessageQueue 吗?我没有很好地理解它们,正如我确信我已经表现出来的那样。谢谢你!
I know the general problem of "Can't create handler inside thread that has not called Looper.prepare()" has been asked before, but I am struggling to understand how it applies in this case.
I am trying to construct a new CountDownTimer in a non-UI thread, which I guess is the cause of this error, but I don't really understand why the timer would need to be used in the main thread. From what I can see, it looks like it has a callback handler that needs to run in a thread that has a looper, which the non-UI thread does not have by default. It seems my options are: 1) Make this non-UI thread have a Looper or 2) make some strange method on my UI thread that can construct this timer, both which seem goofy to me. Can someone help me understand the implications?
Also, does anyone know of any useful links that shed light on the Looper and MessageQueue? I don't grasp them well, as I am sure I have shown. Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CountDownTimer 的实例必须在 UI 线程上创建。
如果您有自定义类对象:
对象的构造必须在 UI 线程上运行
如果多个线程正在创建和销毁计时器,请通过执行以下操作来确保它是在 UI 线程上创建的:
但请注意上面的代码段需要对您的 Activity 和类成员变量 mTimer 的引用
An instance of CountDownTimer must be created on the UI thread.
If you had the custom class object:
The construction of the object must be run on the UI thread
If multiple threads are creating and destroying the timer, make sure it's created on the UI thread by doing something like this:
but notice how the above code segment needs a reference to your Activity and to a class member variable mTimer
计时器不需要位于 UI 线程中。但我的猜测是您正在更新 UI 以显示该线程中的倒计时计数。宇不能这么做。
使用 asynctask 并在
onProgressUpdate
中更新 UIThe timer doesn't need to be in a UI thread. But my guess is you're updating the UI to display the countdown count in that thread. Yu can't do that.
Use an asynctask and update the UI in
onProgressUpdate