CountDownTimer: "Cannot create a handler inside a thread that did not call Looper.prepare ()"

I know that the general problem “Cannot create a handler inside a thread that Looper.prepare () did not call” was asked earlier, but I'm struggling to figure out how this applies.

I am trying to build a new CountDownTimer in a thread other than the UI, which I think is the cause of this error, but I do not understand why the timer should be used in the main thread. From what I see, it looks like it has a callback handler that should execute on a thread with a loopback mechanism, which by default has a thread other than the UI. It seems my options are: 1) Create this thread without a UI with Looper or 2) make some weird method in my UI thread that can build this timer, both seeming silly to me. Can someone help me understand the consequences?

Also, does anyone know of any useful links shedding light on Looper and MessageQueue? I do not understand them well, as I am sure I showed. Thank!

+3
source share
2 answers

The timer does not have to be in the user interface thread. But I assume that you are updating the user interface to display a countdown counter in this thread. Yu cannot do this.

Use asynctask and update the interface in onProgressUpdate

+3
source

An instance of CountDownTimer must be created in the user interface thread.

If you have a custom class object:

public class MyTimer extends CountDownTimer{
    public MyTimer(...){
         super(duration,interval);
    }
    //... other code ...//
}

The design of the object must be performed in the user interface thread.

MyTimer mTimer = new MyTimer(...);   //can throw RuntimeException
                                    // with Looper.prepare() issue if
                                    // caller isn't UI thread

If multiple threads create and destroy a timer, make sure it is created in the user interface thread by doing something like this:

MyActivity.runOnUiThread( new Runnable(){
     public void run(){
          mTimer = new MyTimer(...);
     }
});

, mTimer

+2

Source: https://habr.com/ru/post/1771120/


All Articles