Sunday, February 10, 2013

Timer, not it is Handler.postDelayed

In previous post http://grumpyoldprogrammer.blogspot.com/2013/02/text-to-speech.html I managed to init TTS. Now with talkative Android I can go and implement countdown timer. Whole story with SoundPool and TTS was about I need tool to count for me exposure while I am doing manual tracking. Only that I won’t use Timer or CountDownTimer but ordinary Handler. I leave whole code from TTS how it is and change button onClick listener and add couple of variables. Those are new class variables:

private int counter = 60;
private Handler timer;
boolean timerRunning = false;
private Runnable timerTask = new Runnable() {
    public void run() {
        myTTS.speak(Integer.toString(counter), TextToSpeech.QUEUE_FLUSH, null);
        if (counter > 1) {
            counter-=5;
            timer.postDelayed(timerTask, 5000);
        } else {
            counter = 60;
            timerRunning = false;
        }
    }
};


For more elaborate application I would make counter and delay adjustable but now I like it simple. Don’t forget to create instance of Handler. Now new onClick method:

public void onClick(View v) {
    if (!timerRunning) {
        timerRunning = true;
        timer.post(timerTask);
    }
}


If we do not have active cycle, onClick will start new one. Runnable.run will ask TTS to read counter and decrease it for 5 what matches the second parameter in postDelayed and finally reposts self again using Handler. When counter is 0 we reset it back to 60 and clear flag so that onClick listener can be used again. On emulator execution of 60 seconds countdown takes about 60.3 seconds, so it is not very precise but also not unusable.

No comments:

Post a Comment