Search code examples
javaandroidlimithandlerdelay

Using a handler to delay a repeated task for a limited number of times


I have a program that draws a bunch of red boxes in the shape of a spiral. I have everything working, except I cant figure out how to delay the process so you can see the spiral forming. I had my code in a for loop and moved it to a Runnable with a while loop and a 500ms delay. The program is meant to stop when onClick or if it runs 49 times.

I'm too impatient to see the end result, because my phone just slows down when I start the spiral, and has no animation

Runnable run = new Runnable(){
    @Override
    public void run(){
        if(row>=0 && (dir==0 && (row==6 || grid[row+1][col]!=null)) ||
                (dir==1 && (col==6 || grid[row][col+1]!=null)) ||
                (dir==2 && (row==0 || grid[row-1][col]!=null)) ||
                (dir==3 && (col==0 || grid[row][col-1]!=null)))
            dir++;
        dir=dir%4;
        switch(dir){
            case 0: row++;break; //down
            case 1: col++;break; //right
            case 2: row--;break; //up
            case 3: col--;break; //left
        }
        grid[row][col] = new ImageView(t);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(88, 88);
        layoutParams.setMargins((width/2)-(450)+(88 * row) + (35 * (row + 1))+c, (height/2)-655+(88 * (col+1)) + (35 * (col + 1))+c ,0,0);
        grid[row][col].setLayoutParams(layoutParams);
        grid[row][col].setImageResource(R.drawable.redbox);
        layout.addView(grid[row][col]);
        x++;
        c++;
        c=c%7;
        while(!stop && x<49)
            h.postDelayed(run,500);
    }
};

public void spiral() {
    c=0;
    row=-1;
    col=0;
    dir =0;
    run.run();
}

Solution

  • There are a number of ways to do this, including something like what you have done here. The first thing to do is remove the while() loop at the end of your Runnable and instead just have the Runnable post itself as long as the count is less than 49. What you have now is posting the same Runnable multiple times each time it is run, all triggered to be delivered at the same time to the main Handler.