androidandroid-handlerlooperandroid-looperandroid-thread

Does handler belong to thread in which it was created?


I'm relatively new to the "Looper-Handler" term. I'm pretty clear with the way they work but still confused with their architecture. I've also gone through couple of SO questions, but still I have some questions regarding them.

To get them clear and to summarize, can anyone answer for the below questions?

  1. Is it true that the Handler belong to the thread in which it was created ?
  2. I'm aware that there can be multiple instances of handler per Looper/MeesageQueue pair. Is it possible create a handler for a thread from some other Thread?
  3. Suppose, in the main thread we write Handler handler = new Handler (x.getLooper()) where x is the handler of another thread X, then to which MessageQueue handler will actually post?

If I'm getting wrong anywhere, please make me correct. Thanks.


Solution

    1. Right, if you use default constructor val h = Handler(). Default constructor associates this handler with the Looper for the current thread. If this thread does not have a looper, this handler won't be able to receive messages so an exception is thrown.
    2. Yes. If you use constructor, which accepts Looper val h = Handler(looper), where looper associated with another Thread.
    3. handler will be associated with Thread X, because looper of that thread is used to created the handler.

    The 3rd question is similar to the 2nd one.