I'm trying to make a simple CountDown Timer in Java, that executes a set of instructions repeatedly. I want the user to be able to control the frequency of that execution in real time while the code is running (with a SeekBar on Android). Here is my attempt so far:
final CountDownTimer countDownTimer = new CountDownTimer(rsvp.wordsOfSentence.length * rsvp.pace, rsvp.pace) {
@Override
public void onTick(long millisInFuture) {
targetTextView.setText(rsvp.wordsOfSentence[rsvp.getCurrentWord()]);
rsvp.incrementCurrentWord();
}
@Override
public void onFinish() {
targetTextView.setText(rsvp.wordsOfSentence[rsvp.getCurrentWord()]);
}
};
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
rsvp.setPace(progress);}
});
Method setPace() changes value of int pace (both are set in class RSVP, and rsvp is an object of this class). So I'm trying to pass pace to CountDown Timer as reference, but I'm not sure I do this correctly. Timer executes code, but user has no control over the frequency.
Thanks in advance and forgive me if something is not clear, I just started playing with Java :)
If you want to stick with using CountDownTimer
, you can do this when the seek bar changes:
Alternatively, you can make use the Handler
class's postDelayed
method to do some action after a delay, but this does the action only once, so you need to call it again and again. I think this makes it easier to change the pace since you can just call postDelayed
with a different millisecond number when the seek bar changes.
I have written this little Timer
class which makes use of the above method:
public class Timer {
private Handler handler;
private boolean paused;
private int interval;
private Runnable task = new Runnable () {
@Override
public void run() {
if (!paused) {
runnable.run ();
Timer.this.handler.postDelayed (this, interval);
}
}
};
private Runnable runnable;
public int getInterval() {
return interval;
}
public void setInterval(int interval) {
this.interval = interval;
}
public void startTimer () {
paused = false;
handler.postDelayed (task, interval);
}
public void stopTimer () {
paused = true;
}
public Timer (Runnable runnable, int interval, boolean started) {
handler = new Handler ();
this.runnable = runnable;
this.interval = interval;
if (started)
startTimer ();
}
}
You can easily get and set the interval
field with the getters and setters.
Usage:
Timer timer = new Timer(new Runnable() {
@Override
public void run() {
// code to run in each tick of the timer here...
}
}, someInterval, true);
// the timer will start automatically if you pass true as the third argument.