I'm trying to create an app that mimics a traffic light by looping a segment of code that switches the background of a TextView from red to yellow to green after holding each color for a certain amount of time. The user will be able to start and end the loop by pressing a button. I've used CountDownTimers to hold each background of the TextView for a certain amount of time, and that method seems to be working fine. The current state of my code is as follows:
public void trafficLight() {
lightDisplay.setBackgroundColor(Color.RED);
// Temporary for loop, a do-while loop causes the app to crash
for (int x = 2; x <= 4; x++) {
signalSwitcher(3000, Color.YELLOW);
signalSwitcher(6000, Color.GREEN);
signalSwitcher(9000, Color.RED);
}
}
public void signalSwitcher(long delayTime, final int signalColor) {
new CountDownTimer(delayTime, 1000) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
lightDisplay.setBackgroundColor(signalColor);
}
}.start();
I can't seem to get the code in the trafficLight method to loop, as I haven't found a way to pause the start of another loop iteration before the background change cycle completes. In other words, when I run the code, the loop keeps scheduling the tasks in the CountDownTimers; it doesn't schedule, wait for the tasks to complete, and repeat.
My best attempt at trying to solve this problem consisted of having another do-while loop at the end of the signalSwitcher methods that rechecks a parameter until the last signalSwitcher method provides the input needed to exit that loop. However, it seems that this method doesn't work, as I get a blank screen when I try to run the app.
Simply stated, how can you pause a loop until the code inside CountDownTimers are executed?
I think there is no direct api can pause and resume the timer. But you can just cancel it, then record the remaining time. Recreate a timer with the remaining time.
Instead of for loop, do the changes in CountDownTimer onTick() method. Try with this code.
public void trafficLight() {
lightDisplay.setBackgroundColor(Color.RED);
signalSwitcher(9000);
}
public void signalSwitcher(long delayTime) {
new CountDownTimer(delayTime, 1000) {
@Override
public void onTick(long millisUntilFinished) {
if(millisUntilFinished == 3000)
lightDisplay.setBackgroundColor(Color.YELLOW);
else if(millisUntilFinished == 6000)
lightDisplay.setBackgroundColor(Color.GREEN);
}
@Override
public void onFinish() {
lightDisplay.setBackgroundColor(Color.RED);
}
}.start();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.