gpt4 book ai didi

java - 如何在 android studio CountdownTimer 中的另一个 CountdownTimer 中重新启动(两者都工作正常)

转载 作者:行者123 更新时间:2023-12-01 11:17:38 26 4
gpt4 key购买 nike

我正在尝试制作一个问题游戏来提高我的技能。用户选择游戏时间(在本例中假设为 10 分钟),对于每个问题,他们有 10 秒或其他时间来回答。两个计时器都工作正常,但是当 10 秒计数器到达终点时,如何重新启动并让位于下一个问题,直到 10 分钟计数器结束?

   private void startGameTimer(final TextView gameCountDown, final ArrayList<MusicSQLRow> arrayQuiz) {
// le agrego 2 segundos de delay para que le de tiempo al usuario de reaccionar


new CountDownTimer(gameTime,1000){

@Override
public void onTick(long millisUntilFinished) {

gameCountDown.setText("Time Remaining: "+String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes( millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));

// the questions begin adjusted by the SharedPreferences answer time, se abre otro thread para manejar la pregunta
this.askQuestion(arrayQuiz);

}

// handles just one question
private void askQuestion(ArrayList<MusicSQLRow> arrayQuiz) {

new CountDownTimer(answerTime,1000){


@Override
public void onTick(long millisUntilFinished) {

answerCountDown.setText("Next Question in: "+ TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) );


}

@Override
public void onFinish() {

}
}.start();


}

@Override
public void onFinish() {
//unhide buttons to go back to main menu or to play again(reset the activity, check if there's no problem with shared preferences when the activitie reloads)
}

}.start();

}

最佳答案

首先:尽量不要创建长时间运行的 CountDownTimer 的匿名实例,您将无法处置它们并且会泄漏整个 Activity 。最好的选择是创建包含这些计时器的单独的类文件。

CountDownTimer gameTimer, answerTimer;
boolean gameTimerIsRunning, answerTimerIsRunning;

public void startGame(){
startGameTimer();
startAnswerTimer();
}

public void startGameTimer(){
gameTimer = new CountDownTimer(GAME_DURATION, TEXT_VIEW_UPDATE_RATE){

@Override public void onTick(long millisUntilFinished) {
updateGameTextView(millisUntilFinished);
}

@Override public void onFinish() {
gameTimerIsRunning = false;
if(answerTimerIsRunning) answerTimer.cancel();
handleEndOfTheGame();
}

};
gameTimerIsRunning = true;
gameTimer.start();
}

public void startAnswerTimer(){
if(answerTimer==null) {
answerTimer = new CountDownTimer(TIME_FOR_AN_ANSWER, TEXT_VIEW_UPDATE_RATE) {

@Override public void onTick(long millisUntilFinished) {
updateAnswerTextView(millisUntilFinished);
}

@Override public void onFinish() {
answerTimerIsRunning = false;

if (gameTimerIsRunning) {
loadNewQuestion();
startAnswerTimer();
}
};
}
answerTimerIsRunning = true;
answerTimer.start();
}

不要忘记在 Activity/fragment 的 onPause() 中调用 gameTimer.cancel() 和 answerTimer.cancel()。

关于java - 如何在 android studio CountdownTimer 中的另一个 CountdownTimer 中重新启动(两者都工作正常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31619819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com