In my application the user is prompted with an exercise and he has 5 seconds to solve it, if he does not respond in time, the next exercise should be shown.
My question is: What would be the best way to implement such a behaviour in Android?
I have first tried it with a CountDownTimer
but for some reason the CountDownTimer.cancel()
does not cancel the timer.
My second attempt works, (see below) but it contains a buisy wait and I don't know if that is such a good pattern.
for (int i = 0; i < NUM_EXERCISES; i++) {
// show a new fragment with an activity
fragmentManager.beginTransaction()
.replace(R.id.exercise_container, getNextExercise())
.commit();
// I create a thread and let it sleep for 5 seconds, and then I wait busily
// until either the thread is done or the user answers and I call future.cancel()
// in the method that is responsible for handling the userinput
future = es.submit(()->{
Thread.sleep(5000);
return null;
});
while (!future.isDone()) { }
}
It works like this: I create a Java Future which task it is to just wait 5 seconds and in the callback method, that is responsible for handling the userinput I call future.cancel()
, so the while
loop can be left and the code gets executed further, meaning the for loop does another iteration.
If the user does not respond in time, the while
loop is left after 5 seconds, ensuring that the user does not spend too much time on one exercise.
Feel free to ask for further clarification if needed. Thank you in advance!