File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Looper Handler in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Looper Handler in java" Watch "Looper Handler in java" New topic

Looper Handler in java

muzi bond

Joined: Jul 16, 2010
Posts: 4
The Looper, Handler concept of Android SDK is very kool.
Any ideas to implement similar concept in core java ??
Steve Luke

Joined: Jan 28, 2003
Posts: 4181

I haven't looked at the code, but my guess is this:

The static method Looper.prepare() creates a ThreadLocal reference to a Looper instance. The Looper instance has a Queue (probably a BlockingQueue of some sort) associated with it.
The Handler constructor uses the static method Looper.myLooper() which uses that ThreadLocal reference to return the proper Looper instance to the Handler.
The static method Looper.loop() then causes the Looper instance for the current Thread (the one assigned to the ThreadLocal reference) to run in a loop consuming the Queue, taking messages and calling the Handler's handleMessage() method.
The Handler then can use the Looper instance it retrieved to push messages or actions into the Looper's Queue and therefore into the Looper's thread loop()ing Thread.

Example of what it might look like in code. Untested, so treat it like pseudo-code

muzi bond

Joined: Jul 16, 2010
Posts: 4
I agree. Here's the link:
subject: Looper Handler in java
It's not a secret anymore!