I have a variable in my code say it is \"status\".
I want to display some text in the application depending on this variable value. This has to be done with a speci
For people using Kotlin, inazaruk's answer will not work, the IDE will require the variable to be initialized, so instead of using the postDelayed
inside the Runnable
, we'll use it in an separate method.
Initialize your Runnable
like this :
private var myRunnable = Runnable {
//Do some work
//Magic happens here ↓
runDelayedHandler(1000) }
Initialize your runDelayedHandler
method like this :
private fun runDelayedHandler(timeToWait : Long) {
if (!keepRunning) {
//Stop your handler
handler.removeCallbacksAndMessages(null)
//Do something here, this acts like onHandlerStop
}
else {
//Keep it running
handler.postDelayed(myRunnable, timeToWait)
}
}
As you can see, this approach will make you able to control the lifetime of the task, keeping track of keepRunning
and changing it during the lifetime of the application will do the job for you.