Kotlin - 如何在 Handler 中传递 Runnable

Hay*_*yan 10 android handler runnable kotlin

我是科特林初学者。我尝试创建一个每 2 秒重复一次的任务。所以我创造了这样的东西。

val handler = Handler()
    handler.postDelayed(Runnable {
        // TODO - Here is my logic

        // Repeat again after 2 seconds
        handler.postDelayed(this, 2000)
    }, 2000)
Run Code Online (Sandbox Code Playgroud)

但在 postDelayed(this) 中它给出了错误 - required Runnable!, found MainActivity。我什至尝试过,this@Runnable但没有成功。

但是当我像这样编写相同的函数时,它就可以工作了

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)
Run Code Online (Sandbox Code Playgroud)

那么为什么this关键字在第一个函数中不起作用,但在第二个函数中却很好呢?

Len*_*Bru 6

您在这里有多种选择:

  1. 使可运行对象和处理程序位于同一范围内

        //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)
          }
       }
    
    Run Code Online (Sandbox Code Playgroud)

然后在某个函数中

handler.postDelayed(runnable,time)
Run Code Online (Sandbox Code Playgroud)
  1. 您可以运行 a timertask,在这种情况下会更好

     val task = TimerTask {
        override fun run() {
         //do your thing
        }
     }
    
     val timer = Timer()
    
     timer.scheduleAtFixedRate(task,0L, timeBetweenTasks)
    
    Run Code Online (Sandbox Code Playgroud)