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() {
    @Override
    public void handleMessage(Message msg) {
        // process message from worker thread
        if(msg.what == ADD_MESSAGE) {
            _addMessage((String) msg.obj);
        }
        super.handleMessage(msg);
    }
};

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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: