Accessing UI thread handler from a service
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.
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.
At the moment I prefer using event bus library such as Otto for this kind of problem. Just subscribe the desired components (activity):
protected void onResume() { super.onResume(); bus.register(this);}
Then provide a callback method:
public void onTimeLeftEvent(TimeLeftEvent ev) { // process event..}
and then when your service execute a statement like this:
bus.post(new TimeLeftEvent(340));
That POJO will be passed to your above activity and all other subscribing components. Simple and elegant.