Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing UI thread handler from a service

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

like image 414
iLikeAndroid Avatar asked Jun 16 '11 08:06

iLikeAndroid


People also ask

Does handler run on UI thread?

Short answer: they all run on the same thread. If instantiated from an Activity lifecycle callback, they all run on the main UI thread.

What is the difference between handler and HandlerThread?

The main difference between Handler and Thread is that a handler is a function or a method that is capable of performing a specific task while a thread is a small, lightweight execution unit within a process.


2 Answers

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.

like image 104
volley Avatar answered Sep 21 '22 16:09

volley


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.

like image 37
CommonsWare Avatar answered Sep 24 '22 16:09

CommonsWare