android 处理程序 wait/sleep 不工作

android handler wait/sleep not working

我在实现延迟函数的处理程序时遇到问题。这应该是一个简单的骰子游戏。

当轮到计算机掷骰子时,每次掷骰子之间应该有一个暂停,以便用户可以看到计算机掷的是什么。当我 运行 代码时,它应该等待 2 秒再滚动。这不会发生。

这是我在 Whosebug 上的第一个 post。欢迎提出任何建议。

Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
  @Override
  public void run() {
    timerHandler.postDelayed(this, 2000);  //delay run for 2 seconds
  }
};

public void computerTurn() {
  rollButton.setEnabled(false);   //disable UI for cpu's turn
  holdButton.setEnabled(false);
  ImageView diceImg = (ImageView) findViewById(R.id.dicePic);
  Random r = new Random();

  diceRoll = r.nextInt(6) + 1;
  switch (diceRoll) {
    case 1:
      compTurnScore = 0;
      diceImg.setImageResource(R.drawable.dice1);
      compTurnScoreTxt.setText("Computer Turn Total :" + compTurnScore);
      break;
    case 2: ...
    case 3: ...
    case 4: ...
    case 5: ...
    case 6:
      compTurnScore += 6;
      diceImg.setImageResource(R.drawable.dice6);
      compTurnScoreTxt.setText("Computer Turn Total :" + compTurnScore);
      break;
  }

  timerHandler.postDelayed(timerRunnable, 0);   //run the timerhandler without any delay
  if(compTurnScore < 20)    //if cpu rolls less than 20 keep rolling
    computerTurn();
}

正如我理解的那样,你希望 computerTurn() 执行,这样如果掷骰子发生,只有在需要调用另一个 computerTurn() 时才应使用 dealy 显示([=13 的条件=]).

如果您想使用 Handler,我建议将其视为 "lets call computerTurn() in a delayed fashion from Handler"。代码将是这样的(基于您的原始代码):

Handler timerHandler = new Handler(); // Created in Main thread thus handled in Main thread
Runnable timerRunnable = new Runnable() {
  @Override
  public void run() {
    computerTurn(); // Called in Main thread
  }
};

public void computerTurn() {
  rollButton.setEnabled(false);   //disable UI for cpu's turn
  holdButton.setEnabled(false);
  ImageView diceImg = (ImageView) findViewById(R.id.dicePic);
  Random r = new Random();

  diceRoll = r.nextInt(6) + 1;
  switch (diceRoll) {
    case 1:
      compTurnScore = 0;
      diceImg.setImageResource(R.drawable.dice1);
      compTurnScoreTxt.setText("Computer Turn Total :" + compTurnScore);
      break;
    case 2: ...
    case 3: ...
    case 4: ...
    case 5: ...
    case 6:
      compTurnScore += 6;
      diceImg.setImageResource(R.drawable.dice6);
      compTurnScoreTxt.setText("Computer Turn Total :" + compTurnScore);
      break;
  }

  if(compTurnScore < 20) {   //if cpu rolls less than 20 keep rolling
    timerHandler.postDelayed(timerRunnable, 2000);   //request another round of computerTurn() to be called after 2 sec
  }
}

请注意,这里可能会有一些泄漏,因为 computerTurn() 可以在 ActivityFragment 上下文可能不再存在时调用。按照其他帖子了解如何检查 ActivityFragment 是否仍处于状态,以便您可以安全地访问它的视图。