display data after every 10 seconds in Android

Farha Ansari picture Farha Ansari · Mar 29, 2010 · Viewed 62.3k times · Source

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

Answer

Rahul Patel picture Rahul Patel · Mar 29, 2010

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