Android UI How to - Use Handler class to Update UI from another thread








A Handler enables you to send and process messages, similar to using the post() method of a View.

The following code shows how to Use Handler class to Update UI from another thread.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />

<Button
    android:id="@+id/btnStartCounter"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Start"
    android:onClick="startCounter" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TextView" />

</LinearLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
/*  ww w  .  ja v a  2 s. c  o m*/

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
    static TextView txtView1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtView1 = (TextView) findViewById(R.id.textView1);
    }

    static Handler UIupdater = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            byte [] buffer = (byte []) msg.obj;
            String strReceived = new String(buffer);
            txtView1.setText(strReceived);
        }
    };

    public void startCounter(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0; i<=1000; i++) {
                    MainActivity.UIupdater.obtainMessage(
                            0,  String.valueOf(i).getBytes() ).sendToTarget();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        Log.d ("Threading", e.getLocalizedMessage());
                    }
                }
            }
        }).start();
    }
}