views:

526

answers:

3

I have to display some data after every 10 seconds. Can anyone tell me how to do that?

A: 

Probably the simplest thing to do is this:

while(needToDisplayData)
{
    displayData(); // display the data
    Thread.sleep(10000); // sleep for 10 seconds
}

Alternately you can use a Timer:

int delay = 1000; // delay for 1 sec. 
int period = 10000; // repeat every 10 sec. 
Timer timer = new Timer(); 
timer.scheduleAtFixedRate(new TimerTask() 
    { 
        public void run() 
        { 
            displayData();  // display the data
        } 
    }, delay, period); 
Lirik
A: 

There is an another way also that you can use to update the UI on specific time interval. Above two options are correct but depends on the situation you can use alternate ways to update the UI on specific time interval.

First declare one global varialbe for Handler to update the UI control from Thread, like below

Handler mHandler = new Handler();

Now create one Thread and use while loop to periodically perform the task using the sleep method of the thread.

 new Thread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                try {
                    Thread.sleep(10000);
                    mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            // Write your code here to update the UI.
                        }
                    });
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }
    }).start();
Rahul Patel
+2  A: 

Andrahu was on the right track with defining a handler. If you have a handler that calls your update functions you can simply delay the message sent to the handler for 10 seconds.

In this way you don't need to start your own thread or something like that that will lead to strange errors, debugging and maintenance problems.

Just call:

 Handler myHandler = new MyUpdateHandler(GUI to refresh); <- You need to define a own handler that simply calls a update function on your gui.
 myHandler.sendMessageDelayed(message, 10000);

Now your handleMessage function will be called after 10 seconds. You could just send another message in your update function causing the whole cycle to run over and over

Janusz
this is the best method, here is a more detailed example http://developer.android.com/resources/articles/timed-ui-updates.html
schwiz