android处理程序等待/睡眠不工作

时间:2016-07-22 07:01:50

标签: android delay handler android-handler

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

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

这是我在stackoverflow上的第一篇文章。欢迎任何建议。

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

1 个答案:

答案 0 :(得分:0)

正确认为你需要执行computerTurn(),如果骰子滚动发生,只有当需要调用另一个computerTurn()时,它才会显示为dealy(条件为compTurnScore < 20 )。

如果您想使用Handler,我建议将其视为&#34;我们可以从computerTurn()&#34;以延迟方式致电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()Activity上下文可能不再存在时,Fragment可能会调用某些泄漏信息。关注如何检查ActivityFragment是否仍然处于状态的其他帖子,以便您可以安全地访问该视图。