NewOne NewOne - 2 months ago 7
Android Question

How to call more than one methods at regular interval using handlers?

I know how to use handler and runnable to call a method at regular intervals of time. But now I want to call more than one method at regular interval of time. Below is the code in one of my classes:

private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
@Override
public void run() {
for(int index = 0; index < count; index++) {
//Do something based on the index value
}
handler.postDelayed(runnable, 500);
}
};


Somewhere in my code I will have the below code to start the execution:

handler.postDelayed(runnable, 0);


So the first method corresponding to index 0 will be called first followed by other methods. And then there will be a 500ms delay to repeat the same.

But I also want a 500ms delay between the method calls. I mean when the for loop is executed. How can I do it using only one handler and runnable? How can I induce a 500ms delay between the method calls?

Answer

I would update the value of index across Handler invocations myself, and compare it to yourcount variable just like the for loop

private Handler handler = new Handler();
 private Runnable runnable = new Runnable() { 
    private int index = 0;

    @Override 
    public void run() { 
        //Do something based on the index value 
        index++;
        if (index < count) {
            handler.postDelayed(runnable, 500); 
        } else {
            count = 0;
        }
    } 
}

Besides, at the start you don't need to invoke postDelayed() with zero delay, you can directly call post().