How to change/reset handler post delayed time?

后端 未结 3 1589
春和景丽
春和景丽 2020-12-09 11:41

I\'m using postDelayed method of the Handler in order to perform an action after certain amount of time:

private static int time_to         


        
相关标签:
3条回答
  • 2020-12-09 11:59

    you can just try

    handler.removeMessage(what)
    handler.sendMessageDelayed(time_to_wait + INTERVER);
    

    every time you need first remove message and then send a new message.

    0 讨论(0)
  • 2020-12-09 12:10

    this can be achieved by easily create a runnable that will be displayed by the handler, then creating the handler as static member, finally when you want to stop it just remove the callback of your created runnable, and if you want to restart it you have to remove the callback and assign it again:

    Runnable myRunnable = new Runnable() {
        @Override
        public void run() {
            // your code here
        }
    };
    
    public static Handler myHandler = new Handler();
    private static final int TIME_TO_WAIT = 2000;
    
    public void start() {
        myHandler.postDelayed(myRunnable, TIME_TO_WAIT);
    }
    
    public void stop() {
        myHandler.removeCallbacks(myRunnable);
    }
    
    public void restart() {
        myHandler.removeCallbacks(myRunnable);
        myHandler.postDelayed(myRunnable, TIME_TO_WAIT);
    }
    
    0 讨论(0)
  • 2020-12-09 12:24

    KOTLIN VERSION: (#Muhammed Refaat's Answer):

    var myHandler = Handler()
    private val TIME_TO_WAIT: Long = 2000
    
    var myRunnable = Runnable {
        // your code here
    }
    
    fun start() {
        myHandler.postDelayed(myRunnable, TIME_TO_WAIT)
    }
    
    fun stop() {
        myHandler.removeCallbacks(myRunnable)
    }
    
    fun restart() {
        stop()
        start()
    }
    
    0 讨论(0)
提交回复
热议问题