tags:

views:

5226

answers:

1

Hi

I developed one small application to display some text at defined intervals in the android emulator screen.I am using Handler class, small snippet from my code

handler=new Handler();
Runnable r=new Runnable()
{
    public void run() 
    {
        tv.append("Hello World");      
    }
};
handler.postDelayed(r, 1000);

When i run this appication the text is displayed only one time.Please any one knows how to run a thread using Handler help me.

+6  A: 

The simple fix to your example is:

final Runnable r = new Runnable()
{
    public void run() 
    {
        tv.append("Hello World");
        handler.postDelayed(this, 1000);
    }
};

handler.postDelayed(r, 1000);

Or we can use normal thread for example (with original Runner):

Thread thread = new Thread()
{
    @Override
    public void run() {
        try {
            while(true) {
                sleep(1000);
                handler.post(r);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};

thread.start();

You may consider your runnable object just as a command that can be sent to the message queue for execution, and handler as just a helper object used to send that command.

More details are here http://developer.android.com/reference/android/os/Handler.html

alex2k8
Thanks for your Response.
Rajapandian
Alex, i have one small doubt.Now the thread is running perfectly and displaying the text continously, if i want to stop this means what i have to do?Please help me.
Rajapandian
You may define boolean variable _stop, and set it 'true' when you want to stop. And change 'while(true)' into 'while(!_stop)', or if the first sample used, just change to 'if(!_stop) handler.postDelayed(this, 1000)'.
alex2k8