Thursday, December 22, 2011

Sample Handler Implementation

Handler is a verry useful and powerful component in Android. Some special features of Handler are,

     If handler is created without any parameter, then it will be created in the same thread itself.
     We can pass data to handler using message

I have created the below sample application, which is using handler efficiently. Increment the count for one second.

So if we need to create a seperate thread for handler, first we need to create a thread and create the handler inside it.

MainActivity
public class MainActivity extends Activity {
    TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.TextView01);
        new Thread() {
            public void run() {
                int i = 0;
                while (i <= 100) {
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    messageHandler.sendMessage(Message
                            .obtain(messageHandler, i));
                    i++;
                }
            }
        }.start();
    }
    private Handler messageHandler = new Handler() {
        public void handleMessage(Message msg) {
            tv.setText(msg.what + "");
        }
    };
}


Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<TextView android:text="@+id/TextView01" android:id="@+id/TextView01"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:textSize="25dip" android:layout_gravity="center"
    android:layout_marginTop="150dip"></TextView>
</LinearLayout>