Issue
I'm beginner in kotlin. I try to create a task that will repeat every 2 seconds. So I created something like this.
val handler = Handler()
handler.postDelayed(Runnable {
// TODO - Here is my logic
// Repeat again after 2 seconds
handler.postDelayed(this, 2000)
}, 2000)
But in postDelayed(this) it gives error - required Runnable!, found MainActivity. I've tried even this@Runnable but it didn't work.
But when I write the same function like this, it works
val handler = Handler()
handler.postDelayed(object : Runnable {
override fun run() {
// TODO - Here is my logic
// Repeat again after 2 seconds
handler.postDelayed(this, 2000)
}
}, 2000)
So why the this keyword doesn't work in first function, but in second function it works good?
Solution
You have several options to go about here:
make both the runnable and the handler be in the same scope
//class scope val handler = Handler() val runnable = object : Runnable { override fun run () { handler.removeCallbacksAndMessages(null) //make sure you cancel the previous task in case you scheduled one that has not run yet //do your thing handler.postDelayed(runnable,time) } }
then in some function
handler.postDelayed(runnable,time)
You can run a
timertask, which would be better in this caseval task = TimerTask { override fun run() { //do your thing } } val timer = Timer() timer.scheduleAtFixedRate(task,0L, timeBetweenTasks)
Answered By - Lena Bru
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.