Question

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

private static int time_to_wait = 2000;

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  public void run() {
    // Make Action
  }
}, time_to_wait);

now in the middle of the waiting time i want to change the value of the remaining milliseconds due to some processing results, let's say it now waited 1000 ms and i want to make it begins to count from 2000 again, So, i set the time_to_wait value to 2000 but it doesn't take that in count as it only takes the var value (2000) and just waits that time regardless changing the time_to_wait value to any other value.

Was it helpful?

Solution

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);
}

OTHER TIPS

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.

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()
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top