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 believe for this typical case, i.e. to run something with a fixed interval,
Timer
is more appropriate. Here is a simple example:Using
Timer
has few advantages:schedule
function argumentsmyTimer.cancel()
myTimer.cancel()
before scheduling a new one (if myTimer is not null)now in Kotlin you can run threads this way:
The simple fix to your example is :
Or we can use normal thread for example (with original Runner) :
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
An interesting example is you can continuously see a counter/stop-watch running in separate thread. Also showing GPS-Location. While main activity User Interface Thread is already there.
Excerpt:
To look at code see here:
Thread example displaying GPS Location and Current Time runnable alongside main-activity's User Interface Thread
Kotlin
Java