在类中创建 Handler 时不会出现错误“Looper 未准备好”?
在我的游戏中,有一个游戏对象类需要使用Handler来发布延迟Runnable。但是,当我尝试在对象类中创建处理程序时,我会收到错误消息:
无法在线程内创建处理程序 尚未调用 Looper.prepare()
我用 Google 搜索了一些解决方案,但它们都使用另一种解决方案,而不是 Handler。有什么解决方案可以在普通类中使用 Handler 吗?或者有什么解决方案可以在确定的延迟后运行 Runnable 吗?
我无法使用睡眠,因为它暂停了我的所有游戏!
谢谢。
In my game, there is an game object class that need to use Handler to post a delay Runnable. However, everything I try to create an Handler in the object class, I receive error message:
Can't create handler inside thread
that has not called Looper.prepare()
I've Googled some solution, but all of them use another solution, not Handler. Is there any solution to use Handler in a normal class? Or any solution to run a Runnable after a determined delay?
I can't use sleep, because it paused all my game!
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能正在从非 UI 线程创建
Handler
。 (1) 通过将 UI 线程的循环器传递给 Handler 的构造函数,将处理程序显式附加到 UI 线程,这意味着发布到 Handler 的消息也会在UI 线程,或者 (2) 为非 UI 线程创建一个新的Looper
:请参阅 此处。关于 (1) 的编辑:您必须以某种方式将 UI 线程的循环器传递给“游戏对象”,例如在创建它时。您可以通过在上下文(例如,从活动)上调用
getMainLooper()
来获取 UI 循环器的引用。另一种方法是在活动中创建处理程序并将处理程序传递给您的游戏对象。
You are probably creating the
Handler
from a non-UI thread. Either (1) you attach your handler explicitly to the UI thread by passing the UI thread's looper toHandler
s constructor, which means that messages posted to theHandler
are also executed on the UI thread, or (2) you create a newLooper
for the non-UI-thread: see here.edit regarding (1): you would have to somehow pass the UI thread's looper to the "game object", for example when it is created. You can get a reference to UI's looper by calling
getMainLooper()
on a context (e.g. from an activity).An alternative would be to create the handler in the activity and just pass the handler to your game object.