How to run a Runnable thread in Android at defined intervals?
The simple fix to your example is :
handler = new Handler();final Runnable r = new Runnable() { public void run() { tv.append("Hello World"); handler.postDelayed(this, 1000); }};handler.postDelayed(r, 1000);
Or we can use normal thread for example (with original Runner) :
Thread thread = new Thread() { @Override public void run() { try { while(true) { sleep(1000); handler.post(this); } } catch (InterruptedException e) { e.printStackTrace(); } }};thread.start();
You may consider your runnable object just as a command that can be sent to the message queue for execution, and handler as just a helper object used to send that command.
More details are here http://developer.android.com/reference/android/os/Handler.html
new Handler().postDelayed(new Runnable() { public void run() { // do something... }}, 100);
I think can improve first solution of Alex2k8 for update correct each second
1.Original code:
public void run() { tv.append("Hello World"); handler.postDelayed(this, 1000);}
2.Analysis
- In above cost, assume
tv.append("Hello Word")
cost T milliseconds, after display 500 times delayed time is 500*T milliseconds - It will increase delayed when run long time
3. Solution
To avoid that Just change order of postDelayed(), to avoid delayed:
public void run() { handler.postDelayed(this, 1000); tv.append("Hello World");}