英文:
Why does my Timer crashes my android activity when I stop it?
问题
我正在尝试制作一个切换按钮,可以停止和重新启动计时器(Timer),在我添加了一个名为 "Set_BPM" 的新方法之后,它的工作正常。它能够正确启动和停止,但在我在停止后尝试重新启动它时崩溃了。
**这是我在其中使用计时器的类:**
public class Metronome {
int miliseconds;
Timer timer = new Timer();
public Metronome () { }
public void Set_BPM (int bpm) {
miliseconds = (60000 / bpm);
}
public void Start (final Context context) {
TimerTask timerTask = new TimerTask () {
@Override
public void run() {
Sonidos.Tick(context);
}
};
timer.schedule(timerTask, 1000, miliseconds);
}
public void Stop () {
timer.cancel();
timer.purge();
}
}
这是我如何调用它的方式:
public void Encender_Metronomo (View view) {
if (tb_metronome.isChecked()) {
metronome.Set_BPM(Integer.parseInt(et_bpm.getText().toString()));
metronome.Start(this);
}
else
metronome.Stop();
Sonidos.Button(this);
}
**此外,在我的 Activity 顶部还有这个对象:**
private Metronome metronome = new Metronome();
英文:
I'm trying to make a toggle button that can stop and replay a Timer, it worked just fine until I added a new method called "Set_BPM".
It starts and it stops correctly, it crashes when I try to start it again after I stopped it.
This is the class where I'm using the Timer:
public class Metronome {
int miliseconds;
Timer timer = new Timer();
public Metronome () { }
public void Set_BPM (int bpm) {
miliseconds = (60000 / bpm);
}
public void Start (final Context context) {
TimerTask timerTask = new TimerTask () {
@Override
public void run() {
Sonidos.Tick(context);
}
};
timer.schedule(timerTask, 1000, miliseconds);
}
public void Stop () {
timer.cancel();
timer.purge();
}
}
And this is how I'm calling it:
public void Encender_Metronomo (View view) {
if (tb_metronome.isChecked()) {
metronome.Set_BPM(Integer.parseInt(et_bpm.getText().toString()));
metronome.Start(this);
}
else
metronome.Stop();
Sonidos.Button(this);
}
There's also this object on top of my Activity:
private Metronome metronome = new Metronome();
答案1
得分: 0
一旦您调用cancel()
方法取消了一个Timer
,您将无法再安排更多的任务在其上。引用文档:
> 一旦定时器被终止,它的执行线程将会优雅地终止,而且无法再在其上安排更多任务。
英文:
Once you cancel()
a Timer
, you cannot schedule more tasks with it. Quoting the documentation:
> Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论