Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How the handler object get the reference of UI thread?

 
Thennam Pandian
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am just beginner in android. I came to know that using "android.os.Handler" we can run the GUI related code in GUI thread from non-GUI thread.

I am wondering how the handler object hold the reference of the GUI thread. Because when we create the handler object we are not passing any reference to the GUI thread.

Please clarify me, how it get the reference on this.
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not sure about the details (you can look up those in the source code of the Handler class), but obviously somehow from the Android OS itself.

If you want to implement background processing that needs to update the UI, I advise to use AsyncTask instead, though: http://android-developers.blogspot.de/2009/05/painless-threading.html
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Handler doesn't have any special code for working with the GUI thread - rather it makes sure all messages are delivered to the Thread in which the Handler was created. This helps you deliver messages to the GUI thread only when you create the Handler in the GUI thread (then access it from other threads.) If you started the Handler in some other thread that was not the GUI thread you could not send messages to the GUI thread.

Knowing this, it is just a matter of using Thread.currentThread() during the initialization process to get a reference to the Thread in which the Handler was created.
 
Thennam Pandian
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Luke,

Thanks for your reply.

Is the Handler follows event queue mechanism ?
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sort of. It uses a MessageQueue. Essentially the EventQueue is just a MessageQueue associated with the GUI. For a Handler created in the GUI thread you would consider it as working with the EventQueue. But the Handler works with the current Thread's Looper/MessageQueue and not all threads initially have a Looper or MessageQueue, so if you use Handler (or call Looper.prepare()) then a MessageQueue will be created for the current thread if it does not already exist. This could mean that you have multiple different threads running event-like messaging loops.
 
Thennam Pandian
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Steve & Dittmer.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic