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:开发者_StackOverflow
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.
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 to Handler
s constructor, which means that messages posted to the Handler
are also executed on the UI thread, or (2) you create a new Looper
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.
精彩评论