Android: update UI from non-UI worker thread

Today I’m working on TCP/IP socket client module for android java application.
There are 2 threads: worker thread to receive messages from server and initial UI thread.
Unfortunately, it’s impossible to change UI elements from a non-UI thread.
I use android.os.Handler to send some message from non-UI (worker) thread to UI.

import android.os.Handler;

private Handler _handler;

// in UI thread
_handler = new Handler() {
    public void handleMessage(Message msg) {
        // process message from worker thread
        if(msg.what == ADD_MESSAGE) {
            _addMessage((String) msg.obj);

// send message from worker thread to UI
Message msg = EchoClientActivity.this._handler.obtainMessage();
msg.what = ADD_MESSAGE;
msg.obj = message;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: