0

I want to know how I would add a delay in a for loop in android studio. I want to change the background of a button to a certain colour then change it back. Then I want to go on to the next iteration of the loop.

I tried using handlers and the count down timer but I am not getting the desired effect. The loop will not pause and wait.

This is what I essentially want to do:

Random rand = new Random();
int [] pattern = new int[score + 1];
for (int j = 0; j < score+1; j++) {
    pattern[j] = rand.nextInt(4);
//Here what I want is depending on the number, 
  I will change the colour and wait for a second then change it back all before the next iteration starts.
}
Geralt
  • 163
  • 1
  • 7
  • 1
    https://stackoverflow.com/questions/17237287/how-can-i-wait-for-10-second-without-locking-application-ui-in-android – jhayjhay Jan 08 '19 at 01:19
  • If the problem is that the Timer or Thread.sleep will lock de UI, then you can make a service with an alarm with repeat or a thread.sleep and every X seconds then fire a broadcast service (inside the service) and finally listen this BROADCAST (in the MainActivity or the UI) and change your color here – exequielc Jan 09 '19 at 12:44

2 Answers2

0

Thread.sleep ?

Oracle - pausing execution with sleep

0

You can archive with a TimerTask

TimerTask uploadCheckerTimerTask = new TimerTask(){ 
    public void run() { 
       System.out.println("timer_task");
     /*
         rest of your code (change the color here)
     */
    } 
}; 
Timer uploadCheckerTimer = new Timer(true); 
uploadCheckerTimer.scheduleAtFixedRate(uploadCheckerTimerTask, 0, 60 * 1000); 

The advantage of TimerTask is that is easy to impelent and it already has the cancel() feature implemented.

exequielc
  • 681
  • 1
  • 11
  • 32