Accessing UI thread handler from a service

Viewed 82357

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

7 Answers

I suggest trying following code:

    new Handler(Looper.getMainLooper()).post(() -> {

        //UI THREAD CODE HERE



    });

In kotlin thats how you can do it

Let say if you want to show Toast message from service

val handler = Handler(Looper.getMainLooper())
handler.post {
   Toast.makeText(context, "This is my message",Toast.LENGTH_LONG).show()
}
Related