Thursday, November 8, 2012

Update Android UI From Other Threads

Asynchronous functions are useful to run code in background so the UI will not freeze.

Those functions can't access the UI directly because they aren't running in the UI thread.

If you try to access the UI from those threads you will get the error:
"Only the original thread that created a view hierarchy can touch its views."

The solutions is to use Handlers.
private Handler YOURHANDLER = new Handler() {
    public void handleMessage(Message msg) {
        //do some code in the UI thread

    Message Msg = new Message();
    Msg.obj = "SOME TEXT"; //can be any object
In the example, the ASYNCHRONOUSFUNCTION function runs in another thread.

The Message object will contain any information in it's obj property that you want to send to the handler.

Finally, you invoke the sendMessage method of the YOURHANDLER handler.

No comments:

Post a Comment