Simple CountDownTimer Example


NOTE: Improved example here: http://w2davids.wordpress.com/android-listview-with-seekbar-and-button-countdowntimer/

Android comes with a built-in class for constructing CountDownTimers. Its easy to use, efficient and works..(that goes without saying!).

1. Create a subclass of CountDownTimer.
2. Override the onTick() and onFinish() methods.
3. Instantiate a new instance in your Android Activity,
4. Call the start() method on the new instance created!

Download: http://www.filefactory.com/file/cbbbc38/n/SimpleCountDownTimerExample.zip

File: main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<Button
		android:id="@+id/button"
		android:text="Start"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content" />
	<TableLayout
		android:padding="10dip"
		android:layout_gravity="center"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content">
		<TableRow>
			<TextView
				android:id="@+id/timer"
				android:text="Time: "
				android:paddingRight="10dip"
				android:layout_width="wrap_content"
				android:layout_height="wrap_content" />

			<TextView
				android:id="@+id/timeElapsed"
				android:text="Time elapsed: "
				android:paddingRight="10dip"
				android:layout_width="wrap_content"
				android:layout_height="wrap_content" />
		</TableRow>
	</TableLayout>
</LinearLayout>

File: Main.java

package com.examples;

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

public class Main extends Activity implements OnClickListener
	{
		private static final String tag = "Main";
		private MalibuCountDownTimer countDownTimer;
		private long timeElapsed;
		private boolean timerHasStarted = false;
		private Button startB;
		private TextView text;
		private TextView timeElapsedView;

		private final long startTime = 50000;
		private final long interval = 1000;

		/** Called when the activity is first created. */
		@Override
		public void onCreate(Bundle savedInstanceState)
			{
				super.onCreate(savedInstanceState);
				setContentView(R.layout.main);
				startB = (Button) this.findViewById(R.id.button);
				startB.setOnClickListener(this);

				text = (TextView) this.findViewById(R.id.timer);
				timeElapsedView = (TextView) this.findViewById(R.id.timeElapsed);
				countDownTimer = new MalibuCountDownTimer(startTime, interval);
				text.setText(text.getText() + String.valueOf(startTime));
			}

		@Override
		public void onClick(View v)
			{
				if (!timerHasStarted)
					{
						countDownTimer.start();
						timerHasStarted = true;
						startB.setText("Start");
					}
				else
					{

						countDownTimer.cancel();
						timerHasStarted = false;
						startB.setText("RESET");
					}
			}

		// CountDownTimer class
		public class MalibuCountDownTimer extends CountDownTimer
			{

				public MalibuCountDownTimer(long startTime, long interval)
					{
						super(startTime, interval);
					}

				@Override
				public void onFinish()
					{
						text.setText("Time's up!");
						timeElapsedView.setText("Time Elapsed: " + String.valueOf(startTime));
					}

				@Override
				public void onTick(long millisUntilFinished)
					{
						text.setText("Time remain:" + millisUntilFinished);
						timeElapsed = startTime - millisUntilFinished;
						timeElapsedView.setText("Time Elapsed: " + String.valueOf(timeElapsed));
					}
			}
	}

11 thoughts on “Simple CountDownTimer Example

    • if (!timerHasStarted) means if it hasn’t started to show “Start”.
      the ‘!’ sign before a condition, compares the OPPOSITE of the condition. For example:
      (if 3 isn’t 4) is the same as if (3!=4)
      So the code is correct.

  1. Can anyone help? I’m trying to create a events count down timer for my application…
    I understand the Hours and Min and MS to count down, but I want it to count down from a spacific month, day, hour, mins, sec. Any help would be great.

    Thanks,
    Steven S.

  2. I came across this example in Android Cookbook. Despite copy and pasting both the Java code and the XML, no numbers appear when I run it on my AVD (2.3.3). Any idea what the problem may be?

  3. This is a really poorly done example. There is no explanation whatsoever. And what kind of timer only has a reset and a start button? Especially if they are the same button. I’m new to android and I’m very dissapointed at the number of android tutorials out there like this that think no explanation and just a code sample constitues as a learnable tool.

    To the Guest asking about how to cancel the timer, there is a cancel() method you can call.
    i.e. countDownTimer.cancel(); You should probably create a separate button to do this.

    To Steve, you may have to just do the math and figure out how many days, weeks, etc. are in the remaining time. Sorry, I don’t know a better way.

    To JDolan, I believe the text is being written to the wrong location. I fixed it by changing to and adding
    android:paddingTop=”50dip”
    in each TextView. Like this:

    That way the numbers are written right below the button. I have found formatting can be tricky with LinearLayout and you are usually able to do nicer formats with RelativeLayout.
    Also if this confused anybody, the MalibuCountDownTimer is necessary because CountDownTimer is an abstract class meaning that you can only use it by making an inherited class which is what this example used.

    Good luck guys!

  4. Pingback: GPS connection delay : Android Community - For Application Development

  5. i want to make an app with the count down timer
    while clicking the buton the value increment and after 60 seconds the button should be disabled

  6. This is a good example but I think the “RESET” adds an unneeded level of complexity to the example, for demonstration purposes I suggest removing the “RESET” part of the code.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s