I have the code that is attached below. The purpose is just to test canceling the scheduled task created with Handler. Inside the onCreate
function I defined runnable
, which I passed as an argument to both schedule
and cancel
function. My goal is to schedule the function, but cancel it before it comes to its execution. I am trying to cancel the scheduled task with removeCallbacks
function. I also did try using function removeCallbacksAndMessages
passing null
as an argument, as well as passing Integer value as a token, which I passed as well inside the postDelay
function. None of the mentioned did not cancelled the scheduled task
function. Many thanks for any of your help.
class MyFragment: Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val runnable = Runnable {
task()
}
this.schedule(runnable)
this.cancelSchedule(runnable)
}
fun schedule(runable: Runnable) {
Log.d("Schedule", "schedule")
Handler(Looper.getMainLooper()).postDelayed(runable, 5000)
}
fun cancelSchedule(runable: Runnable) {
Log.d("Cancel", "cancele")
Handler(Looper.getMainLooper()).removeCallbacksAndMessages(runable)
}
fun task(){
Log.d("TASK", "run")
}
}
CodePudding user response:
Every Handler instance has its own message queue. Since you keep creating new Handlers in both your schedule
and cancelSchedule
functions, you are not working with the same queue.
You need a single Handler instance to be able to do this, so you should store it in a property.
class MyFragment: Fragment() {
private val handler = Handler(Looper.getMainLooper())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val runnable = Runnable {
task()
}
this.schedule(runnable)
this.cancelSchedule(runnable)
}
fun schedule(runable: Runnable) {
Log.d("Schedule", "schedule")
handler.postDelayed(runable, 5000)
}
fun cancelSchedule(runable: Runnable) {
Log.d("Cancel", "cancele")
handler.removeCallbacksAndMessages(runable)
}
fun task(){
Log.d("TASK", "run")
}
}