Thursday, April 19, 2012

A simple Countdown Timer in Android

Of course we can implement a simple timer using threads but there's a better way out of the box.
     The Android SDK offers us a rather simple way to use timers in our apps,
Let's see how it works:

CountDownTimer timer = new CountDownTimer(maxmillis, 1000) {

@Override
public void onTick(long lastknowtimer) {

int seconds = (int) (lastknowtimer / 1000) % 60 ;
int minutes = (int) ((lastknowtimer / (1000*60)) % 60);  

tvTimerLabel.setVisibility(View.VISIBLE);
tvTimer.setText(String.valueOf(minuts*seconds));  

  }

@Override
public void onFinish() {
tvTimer.setText("finished");
}
};

The abstract class -  CountdownTimer's constructor receives two parameters (maxmillis which is the amount of milliseconds to countdown from, and the second parameter is the interval in which the tick happens).It has two methods which must be implemented: 

1. onTick()  - the action which should happen on every tick (such as updating the display with the current 
state of the timer). 

2. onFinish()  - which should include the code that should be executed when the Countdown timer is done.


have fun with it