Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display data after every 10 seconds in Android

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

like image 884
Farha Ansari Avatar asked Mar 29 '10 04:03

Farha Ansari


People also ask

How do you call every 10 seconds on Android?

This example demonstrates how do I run a method every 10 seconds in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How do you repeat a task on android?

Use a Handler in the onCreate() method. Its postDelayed() method causes the Runnable to be added to the message queue and to be run after the specified amount of time elapses (that is 0 in given example). Then this will queue itself after fixed rate of time (1000 milliseconds in this example).

What is a handler in Android?

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 a Looper .


1 Answers

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(); 
like image 192
Rahul Patel Avatar answered Sep 28 '22 00:09

Rahul Patel