在我的应用程序中,用户会收到一个练习提示,他有 5 秒钟的时间来解决它,如果他没有及时响应,应该显示下一个练习。
我的问题是:在 Android 中实现这种行为的最佳方式是什么?
我首先尝试使用 aCountDownTimer
但由于某种原因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 循环进行另一次迭代。
如果用户没有及时响应,while
则在 5 秒后退出循环,确保用户不会在一项练习上花费太多时间。
如果需要,请随时要求进一步澄清。先感谢您!