Android:Timer onTick问题

时间:2011-09-20 10:46:50

标签: android algorithm

嗨,我正在处理我的一个项目然后我遇到了这个问题,我不知道这是一个bug还是我想分享的东西,希望得到一些答案来启发我的一天。所以这就是问题所在:

我为我的项目制作了一个倒数计时器,它将运行2分钟(即120秒)1000是间隔时间(1000ms = 1s)然后我设置一个检查器,一个120的整数(全局声明)将每次计时器滴答时减1。整数将显示在textView倒计时。然后将在整数到达计时器的onFinish时显示一条消息。该消息将通过将声明的整数减去120来为我花费多少时间。

这里的问题是计时器在达到1之前停止,因为它不会被最后一次打勾扣除。最难的部分是有时它会在剩余时间内以4或甚至5停止。任何人可以帮我这个吗?提前谢谢!

这是我的进一步理解的代码:

//declared a timer
int timer = 120;

//starts the timer
gameTimer = new gameTimer(120000, 1000);
    gameTimer.start();

private class gameTimer extends CountDownTimer{
public gameTimer(long startTime, long interval)
{
    super(startTime, interval);
}

public void onTick(long millisUntilFinished)
{
   //on tick deduct timer by 1
  timer -= 1;   
   TextView timer1 = (TextView)findViewById(R.id.textView1);        
   timer1.setText(""+timer);
}

public void onFinish()
{
    //PERFORM END ACTION UPON FINISHING THE GAME
    endtime = 120 - timer;
    TextView endtime1 = (TextView)findViewById(R.id.textView2);
    1.setText(""+endtime);
}
}

1 个答案:

答案 0 :(得分:4)

首先 * :这是扩展 * CountDownTimer的类:

public class GameTimer extends CountDownTimer{

private YourActivity context;
private int timer = 120;
private int endtime;
private TextView timer1,endTime1;

public gameTimer(YourActivity context, long startTime, long interval)
{
    // passing the context of your activity
    this.context = context;

    //get the textView to display results
    timer1 = (TextView)this.context.findViewById(R.id.textView1); 
    endTime1 = (TextView)this.context.findViewById(R.id.textView2);

    super(startTime, interval);
}

public void onTick(long millisUntilFinished)
{
   //on tick deduct timer by 1
  timer -= 1;  

  //override the method runOnUIThread 
  context.runOnUiThread(new Runnable(){

      @override
      public void run(){
         timer1.setText(""+timer);
      }
  });        

}

public void onFinish()
{
    //PERFORM END ACTION UPON FINISHING THE GAME
    endtime = 120 - timer;

     //override the method runOnUIThread 
  context.runOnUiThread(new Runnable(){

      @override
      public void run(){
         endTime1.setText(""+endtime);
      }
  });

}
}

第二:在您的活动中(在方法上 onCreate() ,实现您的 GameTimer 并启动它:

//instanciate the GameTimer and pass the context to it
GameTimer gameTimer = new GameTimer(this, 120000, 1000);
    gameTimer.start();