Question

FOR calling the function after n seconds I use the code below.

 Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
        myFunction();                           
        }
    }, n);

This code uxcetute n times while statement is true but The on the last excuting there's a couple of second "delay"(holdup,retention). How to avoid from this "delay"? may be this(above) decision is not good decision for my task?

full code is here

public void onClick(View v){
    if (v.getId() == bn.getId()) {
        int[] j = { 1, 2 };
        Random ran = new Random();
        int randomstart = ran.nextInt(j.length);
        if (randomstart == 1) {
            new_game();
        } else {
            new_game();
            aiClick();              
        }

        return;
    }
    if (checkWin() == 2) {

        winfinishrandom();
        wins++;
        calc();
        MainActivity.this.draw_flag();


        if (wins - loses == 10) {
            wins = 0;
            loses = 0;
            draws = 0;                                      
        }
        draw_line();

    } else {
        int[] x = { 1, 2 };
        Random random = new Random();
        int randomaray = random.nextInt(x.length);
        if (randomaray == 1) {
            draw_images();
            aiClick();
        } else { 
            draw_images();
            int[] j = { 1000, 2000 };
            Random ran = new Random();
            int randomstart = ran.nextInt(j.length);
            if (randomstart == 1000) {
                // SLEEP 2 SECONDS HERE ...
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        aiClick();
                    }
                }, randomstart);

            } else {
                // SLEEP 2 SECONDS HERE ...
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        aiClick();
                    }
                }, randomstart);
            }
        }

    }


}
Was it helpful?

Solution

If you want to run a method after n seconds then you don't need to mess around with creating new threads there is a built in method called Thread.sleep(time in milliseconds) that is used as follows:

try {
    Thread.sleep(1000); // 1000 ms = 1s however long you want it
} catch (InterruptedException e) {
    e.printStackTrace(); // It can cause exception so needs to be in a try-catch statement
}
//Run the method here
someMethod();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top