Recipe Using a Countdown Timer

The previous recipe is an example of handlers and a functional timer.Another timer is provided with the built-in class CountDownTimer.This encapsulates the creation of a background thread and the handler queuing into a convenient class call.

The countdown timer takes two arguments: the number of milliseconds until the countdown is done and how often in milliseconds to process onTick() callbacks.The onTick() method is used to update the countdown text. Note that otherwise the recipe is identical to the previous recipe.The full activity is shown in Listing 3.7.

Listing 3.7 src/com/cookbook/countdown/ package com.cookbook.countdown;

import; import android.os.Bundle; import android.os.CountDownTimer; import android.view.View; import android.widget.Button; import android.widget.TextView;

public class CountDownTimerExample extends Activity { //keep track of button presses, a main thread task private int buttonPress=0; TextView mButtonLabel;

//count down timer, a background task private TextView mTimeLabel;

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

mTimeLabel = (TextView) findViewById(; mButtonLabel = (TextView) findViewById(;

new CountDownTimer(30000, 1000) {

public void onTick(long millisUntilFinished) { mTimeLabel.setText("seconds remaining: " + millisUntilFinished / 1000);

public void onFinish() {

mTimeLabel.setText("done!"); }

Button startButton = (Button) findViewById(; startButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view){

mButtonLabel.setText("Pressed " + ++buttonPress + " times");

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook

Post a comment