for some reason my timer is running only once:
Code:
int i = 0;
private void startTimer() {
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
@Override
public void run() {
Log.d("DTAG","K1");
if(preferences.getBoolean(IS_RUNNING_KEY, false))
{
Log.d("DTAG","K2");
final int k = i++;
runOnUiThread(new Runnable() {
@Override
public void run() {
timeCounter.setText(""+k);
Log.d("DTAG","K: "+k);
}
});
} else {
Log.d("DTAG","K3");
timer.cancel();
timer.purge();
}
}
};
timer.schedule(task, 1000);
}
Log:
04-12 16:47:32.333 3079-3684/com.michlind.nanytime D/DTAG: K1
04-12 16:47:32.334 3079-3684/com.michlind.nanytime D/DTAG: K2
04-12 16:47:32.338 3079-3079/com.michlind.nanytime D/DTAG: K: 0
That's the expected behaviour of schedule(TimerTask, long)
. From the documentation
Schedule a task for single execution after a specified delay.
Try using scheduleAtFixedRate
instead.
timer.scheduleAtFixedRate(task, 0, 1000);
you can read more here