How to change/reset handler post delayed time?

后端 未结 3 1588
春和景丽
春和景丽 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 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);
    }
    

提交回复
热议问题