【发布时间】:2021-12-04 10:16:39
【问题描述】:
在我的应用程序中,用户会收到一个练习提示,他有 5 秒钟的时间来解决它,如果他没有及时响应,应该显示下一个练习。
我的问题是:在 Android 中实现这种行为的最佳方式是什么?
我首先尝试使用CountDownTimer,但由于某种原因CountDownTimer.cancel() 没有取消计时器。
我的第二次尝试有效,(见下文)但它包含一个忙碌的等待,我不知道这是否是一个很好的模式。
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()) { }
}
它的工作原理是这样的:我创建了一个 Java Future,它的任务是等待 5 秒,并在回调方法中负责处理我调用 future.cancel() 的用户输入,因此可以留下 while 循环并且代码会进一步执行,这意味着 for 循环会进行另一次迭代。
如果用户没有及时响应,则在 5 秒后退出while 循环,确保用户不会在一项练习上花费太多时间。
如有需要,请随时要求进一步澄清。提前谢谢!
【问题讨论】:
标签: android android-fragments countdowntimer futuretask busy-waiting