In android to which thread's message queue a handler is bound?

575 views Asked by At

I know a handler is bound to the thread's message queue in which it is created, but what if i create a handler in a service and posting a runnable declared in activity to which my service is bound. For example: In service:-

Handler handler=new Handler();
handler.post(Mainactivity.runnable);

In activity inside oncreate method:-

Runnable runnable=new Runnable(){
    public void run{
       //some code here
    }
};

Can someone please explain me what's happening here?

2

There are 2 answers

0
Chetan Joshi On

Please find information about Message Queue and Looper in below link

Understanding Android Core: Looper, Handler, and HandlerThread

In the Android via Looper, Handler, and HandlerThread. The System can be visualized to be a vehicle as in the article’s cover.

1.MessageQueue is a queue that has tasks called messages which should be processed.

2.Handler enqueues task in the MessageQueue using Looper and also executes them when the task comes out of the MessageQueue.

3.Looper is a worker that keeps a thread alive, loops through MessageQueue and sends messages to the corresponding handler to process.

4 Finally Thread gets terminated by calling Looper’s quit() method.

3
arjun On

By default service will run on UI Thread. So the handler you create on service will post the runnable on UI Thread