Search code examples
androidmultithreadinghandlerlooper

Clarification about handler in my code?


This is my code for the handler- attached to message queue of main(ui thread)

handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            progress.setProgress(msg.arg1);
            super.handleMessage(msg);
        }
    };

And the code for a handler sending a message to the message queue of the main thread
private class ProgressThread implements Runnable{

    @Override
    public void run() {
        // TODO Auto-generated method stub
        //reuse message to conserve resources
        Message message = Message.obtain();
        for(int count=0;count<100;count++){
            message.arg1 = count;
            //send message the main thread's message queue
            handler.sendMessage(message);
        }
    }

}

I know that the looper sends messages to the the handler for it to handle the message from the message queue. I also know that broadcast receiver, service, activity, and Content Provider can all post to the message queue. Would my code be flawed in not every message that the Main UI handler handle will have a arg1 set? Im confused because when i ran the code, it ran fine.


Solution

  • AFAIK, even though there might be multiple Handlers associated with a single Looper/MessageQueue, a Handler will only handle Messages that are sent to that same Handler.

    Since no other components will send messages to your Handler, your code is fine.

    I've created a toy project that demonstrates this here.

    The point that I'm trying to make is that even though both Handlers handle Messages in the UI thread, the first Handler will only handle Messages that are sent to it; the same goes for the second Handler. In other words: it's unicast, not broadcast - something that struck me as odd at first too.