首页 > 解决方案 > 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 秒后退出循环,确保用户不会在一项练习上花费太多时间。

如果需要,请随时要求进一步澄清。先感谢您!

标签: androidandroid-fragmentscountdowntimerfuturetaskbusy-waiting

解决方案


应在您的代码中取消计时器。尝试这个 :

        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()


推荐阅读