Muhammed Refaat Muhammed Refaat - 4 months ago 50
Android Question

How to change/reset handler post delayed time?

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.

Answer

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 my_runnable = new Runnable() {
    @Override
    public void run() {
        // your code here
    }
};

public static Handler my_handler = new Handler();
private static int time_to_wait = 2000;

public void start() {
    my_handler.postDelayed(my_runnable, time_to_wait);
}

public void stop() {
    my_handler.removeCallbacks(my_runnable);
}

public void restart() {
    my_handler.removeCallbacks(my_runnable);
    my_handler.postDelayed(my_runnable, time_to_wait);
}

You can have a look at this section of the Handler documentation that explains this process in detail.

Comments