问题
I am writing a quiz program for the Android (written in Java). When the user answers a question (by clicking a button), I want to flash a message on the screen saying whether they were correct or not, followed by a 5 second pause before moving on to the next question.
However, when an answer button is clicked, the program pauses, but does not display the message of correct/incorrect. The message only comes up once the sleep method has finished.
if (correct)
Answer.setText("CORRECT!");
else
Answer.setText("WRONG!");
try { Thread.sleep(5000); }
catch(InterruptedException e) {}
As a bonus, I'd like the answer buttons to be disabled during the pause.
回答1:
Imo AsyncTask
is too much for this usecase.
Don't use sleep. Instead set your correct/incorrect message and than do this:
new Handler().postDelayed(new Runnable(){
public void run()
{
goToNextScreen();
}
}
, 5000);
回答2:
You'll need an AsyncTask for that. Google gives you an intro to it here.
When you Thread.sleep() on the main Activity, you are putting the application to sleep. The AsyncTask will allow you to pause for the 5 seconds, maybe show a little In Progress bar and then pick up from there, without freezing the screen.
回答3:
Use a Handler: you can send a message with a 5000 millisecond delay, disable the buttons and when the message arrives you can re-enable the buttons. See http://www.tutorialforandroid.com/2009/01/using-handler-in-android.html for more info.
回答4:
You should look into using timers for this. I don't think using threads are sensible for this. Using a timer to move onto the next question would work.
Look at timers here
Hope this helps.
Disclaimer: I have only used timers in Java to do something similar but i'm sure it would work in Android.
来源:https://stackoverflow.com/questions/6448253/pause-execution-in-java-gui