gpt4 book ai didi

java - 每次按下按钮时都会创建一个新的计时器实例

转载 作者:行者123 更新时间:2023-12-01 14:17:53 25 4
gpt4 key购买 nike

我正在设计一个递增时钟,它将在单击按钮时执行并更新 TextView 的内容,就像时间流逝一样。但是每次我按下此按钮时,前一个时钟都不会被清除,一个新实例将启动并与前一个线程并行运行。我无法理解如何阻止这种行为。以下是我的代码:

类级别变量:

 int repeatCounter = 1;
CountDownTimer tripTimeCounter;

================================================== ===================================

  private View.OnClickListener but = new View.OnClickListener() {

public void onClick(View v) {
if (isOnline() == true) {
tripTimeCounter = new CountDownTimer(60 * 1000, 1000) {

@Override
public void onFinish() {
// TODO Auto-generated method stub
repeatCounter = repeatCounter + 1;

this.start();
// startTimeCounter();
}

@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
timedisplay = (TextView) findViewById(R.id.textView3);
timedisplay.setText(formatInterval((repeatCounter * 60)
* 1000 - millisUntilFinished));

}

}.start();
tripTimeCounter.start();
} else {
Toast.makeText(getApplicationContext(),
"Not connected to the internet", Toast.LENGTH_LONG)
.show();
}
}
};

最佳答案

只浏览了这一点,但在谷歌搜索计时器后,看到了 cancel方法,其中表示:

When a timer is no longer needed, users should call cancel(), which releases the timer's thread and other resources. Timers not explicitly cancelled may hold resources indefinitely.

关于java - 每次按下按钮时都会创建一个新的计时器实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17940859/

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