I developed an application to display some text at defined intervals in the Android emulator screen. I am using the Handler
class. Here is a snippet from my code:
handler = new Handler();
Runnable r = new Runnable() {
public void run() {
tv.append("Hello World");
}
};
handler.postDelayed(r, 1000);
When I run this application the text is displayed only once. Why?
I think can improve first solution of Alex2k8 for update correct each second
1.Original code:
2.Analysis
tv.append("Hello Word")
cost T milliseconds, after display 500 times delayed time is 500*T milliseconds3. Solution
To avoid that Just change order of postDelayed(), to avoid delayed:
For repeating task you can use
call it like
Where
task being the method to be executed
after the time to initial execution
(interval the time for repeating the execution)
Secondly
And you can also use CountDownTimer if you want to execute a Task number of times.
And you can also do it with runnable. create a runnable method like
And call it in both these ways
OR
If I understand correctly the documentation of Handler.post() method:
So examples provided by @alex2k8, even though are working correctly, are not the same. In case, where
Handler.post()
is used, no new threads are created. You just postRunnable
to the thread withHandler
to be executed by EDT. After that, EDT only executesRunnable.run()
, nothing else.Remember:
Runnable != Thread
.