Thursday, 8 September 2011

Use Handler and Runnable to generate a periodic event

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.



There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.



It's a example using Handler and Runnable to generate a periodic event in 500ms.



Use Handler and Runnable to generate a periodic event



package com.exercise.AndroidHandlerRunnable;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AndroidHandlerRunnableActivity extends Activity {

private int cnt = 0;
Button Start, Stop;
TextView counter;
private Handler handler = new Handler();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter = (TextView)findViewById(R.id.counter);
Start = (Button)findViewById(R.id.Start);
Start.setEnabled(true);
Stop = (Button)findViewById(R.id.Stop);
Stop.setEnabled(false);

Start.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
handler.post(timedTask);
Start.setEnabled(false);
Stop.setEnabled(true);
}});

Stop.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
handler.removeCallbacks(timedTask);
Start.setEnabled(true);
Stop.setEnabled(false);
}});
}

private Runnable timedTask = new Runnable(){

@Override
public void run() {
// TODO Auto-generated method stub
cnt++;
counter.setText(String.valueOf(cnt));
handler.postDelayed(timedTask, 500);
}};
}





<?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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/Start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start"
/>
<Button
android:id="@+id/Stop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Stop"
/>
<TextView
android:id="@+id/counter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>




No comments:

Post a Comment