Call a special method at regular intervals

In my Android application, I want to call a specific method after a regular period of time, i.e. "every 5 seconds" ... how can I do this ??

+6
android android-2.2-froyo
source share
2 answers

You can use Timer to execute a method with a fixed period.

Here is a sample code:

final long period = 0; new Timer().schedule(new TimerTask() { @Override public void run() { // do your task here } }, 0, period); 
+13
source share

This link above is checked and works fine. This is the code to call some method every second. You can change 1000 (= 1 second) at any time (e.g. 3 seconds = 3000)

 public class myActivity extends Activity { private Timer myTimer; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); myTimer = new Timer(); myTimer.schedule(new TimerTask() { @Override public void run() { TimerMethod(); } }, 0, 1000); } private void TimerMethod() { //This method is called directly by the timer //and runs in the same thread as the timer. //We call the method that will work with the UI //through the runOnUiThread method. this.runOnUiThread(Timer_Tick); } private Runnable Timer_Tick = new Runnable() { public void run() { //This method runs in the same thread as the UI. //Do something to the UI thread here } }; } 
+10
source share

All Articles