Use Handler class to Update UI from another thread

Description

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.  j  a  va  2 s  . c  om*/

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();
    }
}




















Home »
  Android »
    Android UI »




UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView