[英]Android: Wait for userinput but set a timeout
在我的應用程序中,提示用戶一個練習,他有 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
循環,確保用戶不會在一項練習上花費太多時間。
如果需要,請隨時要求進一步說明。 先感謝您!
應該在您的代碼中取消計時器。 嘗試這個 :
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()
取消。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.