Accessing UI thread handler from a service
Solution 1:
This snippet of code constructs a Handler associated with the main (UI) thread:
Handler handler = new Handler(Looper.getMainLooper());
You can then post stuff for execution in the main (UI) thread like so:
handler.post(runnable_to_call_from_main_thread);
If the handler itself is created from the main (UI) thread the argument can be omitted for brevity:
Handler handler = new Handler();
The Android Dev Guide on processes and threads has more information.
Solution 2:
Create a Messenger
object attached to your Handler
and pass that Messenger
to the Service
(e.g., in an Intent
extra for startService()
). The Service
can then send a Message
to the Handler
via the Messenger
. Here is a sample application demonstrating this.