Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause while loop until a button is pressed

Tags:

java

android

How do I pause a while loop until a button is pressed?

I want to have a while loop which restarts everytime a button is pressed. Is this possible?

like image 888
Rhiokai Avatar asked Mar 24 '26 08:03

Rhiokai


1 Answers

Answer 1

You could have a button that will exit the loop when it is pressed, and then call the method immediately after it exits.

public void process(){
boolean done = false;
while(!done) {
        // do stuff
        if (buttonPress) done = true;  // ends loop
        else buttonPress = false;  // insures buttonPress is false, not needed
    }
}

Answer 2

You could also just sleep the thread for a certain amount of time, then it will automatically continue when the thread "wakes up".

Thread thread = new Thread() {
boolean isRunning = true;
        public void run() {
             while(isRunning){
                 // do stuff
                 if(buttonPress) Thread.sleep(4000); // or however long you want
             }
        }
    };
    thread.start();

Answer 3

Have a loop within the loop

while(listening) {
    while(!buttonPress) {
    }
    buttonPress=false;
    // do stuff
}
like image 58
syb0rg Avatar answered Mar 26 '26 21:03

syb0rg