readyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
warningLayout.setVisibility(View.GONE);
while(recording){
System.out.println("HELLO");
}
}
});
mainLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
recording = false;
}
});
This is my code, and the idea is that when you click on ready the warningLayout disappears and the loop starts. This loop should be able to stop the while loop when I click on the mainLayout.
The problem is that I've been testing and the error only occurs when I add the while loop to the code, the warningLayout don't dissapear and the clicks don't work, and the loop while works well.
I don't understand why the while loop acts as a blocker.
CodePudding user response:
Right now, the while
-loop has no way of exiting. Once your program enters the loop, it will simply print "HELLO" until the end of time. Your explanation was a little unclear, but it seems to be like you don't need a loop there at all.
However, if you do indeed want a continuous loop to do something until something else causes it to exit, you may want to look into asynchronous method calls.
CodePudding user response:
All click handlers happen on the main (also called UI) thread. WHen a touch happens, the OS adds a message describing the touch to the looper on the main thread. When the main thread is idle, it waits for messages to appear in the looper, and then handles them. If the UI thread doesn't return to the looper, it can't process messages.
In your code, your click handler never returns. So it will loop infinitely, never going back to the looper, thus never handling the other button that would set recording to false. This is why you should never infinitely loop on the UI thread.
If you need to do something like this, you should use a thread or a coroutine to do the loop and print, allowing the main thread to return to idle. Anything else will either freeze the UI or crash from a watchdog timer.