Repeat a task with a time delay?

Kalpa Pathum Welivitigoda picture Kalpa Pathum Welivitigoda · Jun 5, 2011 · Viewed 181.7k times · Source

I have a variable in my code say it is "status".

I want to display some text in the application depending on this variable value. This has to be done with a specific time delay.

It's like,

  • Check status variable value

  • Display some text

  • Wait for 10 seconds

  • Check status variable value

  • Display some text

  • Wait for 15 seconds

and so on. The time delay may vary and it is set once the text is displayed.

I have tried Thread.sleep(time delay) and it failed. Any better way to get this done?

Answer

inazaruk picture inazaruk · Jun 5, 2011

You should use Handler's postDelayed function for this purpose. It will run your code with specified delay on the main UI thread, so you will be able to update UI controls.

private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;

@Override
protected void onCreate(Bundle bundle) {

    // your code here

    mHandler = new Handler();
    startRepeatingTask();
}

@Override
public void onDestroy() {
    super.onDestroy();
    stopRepeatingTask();
}

Runnable mStatusChecker = new Runnable() {
    @Override 
    public void run() {
          try {
               updateStatus(); //this function can change value of mInterval.
          } finally {
               // 100% guarantee that this always happens, even if
               // your update method throws an exception
               mHandler.postDelayed(mStatusChecker, mInterval);
          }
    }
};

void startRepeatingTask() {
    mStatusChecker.run(); 
}

void stopRepeatingTask() {
    mHandler.removeCallbacks(mStatusChecker);
}