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!
An instance of CountDownTimer must be created on the UI thread.
If you had the custom class object:
public class MyTimer extends CountDownTimer{
public MyTimer(...){
super(duration,interval);
}
//... other code ...//
}
The construction of the object must be run on the UI thread
MyTimer mTimer = new MyTimer(...); //can throw RuntimeException
// with Looper.prepare() issue if
// caller isn't 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:
MyActivity.runOnUiThread( new Runnable(){
public void run(){
mTimer = new MyTimer(...);
}
});
but notice how the above code segment needs a reference to your Activity and to a class member variable mTimer
The 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With