Countdown Timer on Android
An exercise I did to practice threading on Android is to implement a simple countdown timer. To do this, I used a Handler and added a Runnable Object—which performs the countdown—to it’s message queue. Here’s a snippet of the Runnable Object:
Runnable mTimerTask = new Runnable() {
@Override
public void run() {
  long currTime = System.currentTimeMillis();
  long currTimeSysClock = SystemClock.uptimeMillis();
  long timeLeftMillis = mWakeUpTime - currTime;
  int seconds = (int) timeLeftMillis / 1000;
  int minutes = seconds / 60;
  int hours = minutes / 60;
  seconds %= 60;
  minutes %= 60;
  updateTime(mSecondView, seconds);
  updateTime(mMinuteView, minutes);
  updateTime(mHourView, hours);

  if (hours == 0 && minutes == 0 && seconds == 0) {
    mTimerHandler.removeCallbacks(this);
  } else {
    mTimerHandler.postAtTime(this, currTimeSysClock + 1000);
  }
  }
};
Finally, passing the Runnable object to the Handler’s post() method will initiate the countdown sequence. Essentially, the run method gets called every 1 second following the first call to run ( postAtTime() ). The process is then repeated until the countdown reaches 0. To prevent reseting the wake up time, the wake up time (mWakeUpTime) is saved in the app’s shared preferences. Another approach that could’ve also been used is through the use of an AsyncTask. However, for a simple task such as a countdown timer and since we want to control the specific time a thread runs, a Handler would be the best way to go.

Comments