Accessing UI thread handler from a service

iLikeAndroid picture iLikeAndroid · Jun 16, 2011 · Viewed 77.8k times · Source

I am trying some thing new on Android for which I need to access the handler of the UI thread.

I know the following:

  1. The UI thread has its own handler and looper
  2. Any message will be put into the message queue of the UI thread
  3. The looper picks up the event and passed it to the handler
  4. The handler handles the message and sends the specfic event to the UI

I want to have my service which has to get the UI thread handler and put a message into this handler. So that this message will be processed and will be issued to the UI. Here the service will be a normal service which will be started by some application.

I would like to know if this is possible. If so please suggest some code snippets, so that I can try it.

Regards Girish

Answer

volley picture volley · Jul 8, 2011

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.