【问题标题】:Timer runs faster every time method is called每次调用方法时计时器运行得更快
【发布时间】:2014-01-30 18:01:44
【问题描述】:

我的 android 应用程序有一点问题。我尝试编写一个计时器,每次按下按钮时都会重新开始。但是如果我这样做,每次调用 timer 方法时,计时器都会变得更快。我不知道,为什么会这样......

public void Dev(View view) {
    cube=(int) (Math.random()*6+1);
    TextView textView = (TextView)findViewById(R.id.textView1);
    textView.setText("Insert number: "+String.valueOf(cube));
    Button play = (Button)findViewById(R.id.button11);
    play.setVisibility(View.INVISIBLE);
    ablauf();   
}

public void ablauf() {
    //progress.cancel();
    progressStatus = 200;
    progressBar = (ProgressBar) findViewById(R.id.progressBar1);
    progressBar.setMax(200);
    progressBar.setProgress(200);

    progress=new Timer();
    tasklol= new TimerTask() {
        public void run() {
            progressmethod();
        }
    };

    progress.scheduleAtFixedRate(tasklol, 0, 30);
}


public void progressmethod() {
    progressBar.setProgress(progressStatus);
    progressStatus=progressStatus-1;

    if(progressStatus<0) {
    }
}

public void stopTimers(){

    progress.cancel();




}

下面是一个调用该方法的 Button 示例:

public void B2 (View view)
{
    if (filled2==false) {
        ablauf();
        stopTimers();
        Button button2 = (Button)findViewById(R.id.button2);
        button2.setText(String.valueOf(cube));
        b=cube;
        TextView textView = (TextView)findViewById(R.id.textView1);
        cube=(int) (Math.random()*6+1);
        textView.setText("Insert number: "+String.valueOf(cube));
        filled2=true;
        counter=counter+1;

        if (counter==9) {
            Berechnen(view);
            textView.setText("Press play to start");
        } else {
            ablauf();
        }
    }
}

如果你能帮助我们 pleeeeeeeeeeeease 那就太好了;)

【问题讨论】:

  • 我猜你有多个定时器线程同时运行。每次调用 ablauf() 都会启动一个新的

标签: android performance methods timer call


【解决方案1】:

您在几个地方调用了 ablauf() 方法,并在该方法中初始化并创建了一个计时器和一个计时器任务,但是您没有正确地停止它们。因此,您有多个计时器正在运行。

【讨论】:

  • 我确实查明了问题所在。他应该在每次用完计时器时停止它,但他没有。
猜你喜欢
  • 1970-01-01
  • 2010-11-13
  • 1970-01-01
  • 1970-01-01
  • 2016-05-12
  • 1970-01-01
  • 1970-01-01
  • 2014-04-24
  • 1970-01-01
相关资源
最近更新 更多