Repeat a task with a time delay?

后端 未结 12 1430
小蘑菇
小蘑菇 2020-11-22 02:14

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

12条回答
  •  星月不相逢
    2020-11-22 02:40

    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.

提交回复
热议问题