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 cod
now in Kotlin you can run threads this way:
class SimpleRunnable: Runnable {
public override fun run() {
println("${Thread.currentThread()} has run.")
}
}
fun main(args: Array<String>) {
val thread = SimpleThread()
thread.start() // Will output: Thread[Thread-0,5,main] has run.
val runnable = SimpleRunnable()
val thread1 = Thread(runnable)
thread1.start() // Will output: Thread[Thread-1,5,main] has run
}
Handler handler=new Handler();
Runnable r = new Runnable(){
public void run() {
tv.append("Hello World");
handler.postDelayed(r, 1000);
}
};
handler.post(r);
private lateinit var runnable: Runnable
override fun onCreate(savedInstanceState: Bundle?) {
val handler = Handler()
runnable = Runnable {
// do your work
handler.postDelayed(runnable, 2000)
}
handler.postDelayed(runnable, 2000)
}
Runnable runnable;
Handler handler;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
// do your work
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
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
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:
public void run() {
handler.postDelayed(this, 1000);
tv.append("Hello World");
}
If I understand correctly the documentation of Handler.post() method:
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
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 post Runnable
to the thread with Handler
to be executed by EDT.
After that, EDT only executes Runnable.run()
, nothing else.
Remember:
Runnable != Thread
.