android - Android:等待用户输入但设置超时
问题描述
在我的应用程序中,用户会收到一个练习提示,他有 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 秒后退出循环,确保用户不会在一项练习上花费太多时间。
如果需要,请随时要求进一步澄清。先感谢您!
解决方案
应在您的代码中取消计时器。尝试这个 :
private var countDownTimer: CountDownTimer? = null
countDownTimer = object : CountDownTimer(10000, 1000) {
override fun onFinish() {}
override fun onTick(millisUntilFinished: Long) {
Log.d("millisUntil", millisUntilFinished.toString())
if ((millisUntilFinished / 1000) <= 5) {
countDownTimer?.cancel()
}
}
}.start()
这是一个 10 秒的计时器,它通过调用 5 秒取消countDownTimer?.cancel()
。
推荐阅读
- flutter - 使用 InkWell 更改卡片颜色和文本
- c - 矩阵 1 和 2 与 C 中的“AND”和“OR”运算的逻辑乘法
- sql - SQl - 如何在彼此相隔 7 天内抓取重复记录
- kubernetes - 如何让 Ingress 与具有所需端口的游戏服务器一起使用 azure 上的 nodeports
- arrays - 索引超出范围,如果不是。VB.net
- python - 来自子目录的 Python 项目组织
- c++ - 未定义对符号“_ZN5boost6system15system_categoryEv”的引用
- python-3.x - 在两个嵌套的 for 循环之间初始化一个变量
- c# - 多行文本块中的自动调整字体大小
- c - C 结构指针和引用的指针