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:
JavaScript
x
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:
JavaScript
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:
JavaScript
private Metronome metronome = new Metronome();
Advertisement
Answer
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.