Thursday, January 9, 2014

Countdown example in Android | Custom timer example in Android | Start, Pause, Stop digital watch code in Android | Java code for timer

Hello Friends,

Today I am going to share code for countdown in android.

Screen shot:


MainActivity.java

 package com.manish.timer;  
 import java.util.concurrent.TimeUnit;  
 import android.annotation.SuppressLint;  
 import android.annotation.TargetApi;  
 import android.app.Activity;  
 import android.os.Build;  
 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;  
 @TargetApi(Build.VERSION_CODES.GINGERBREAD)  
 @SuppressLint("NewApi")  
 public class MainActivity extends Activity {  
      Button btnStart, btnStop;  
      TextView textViewTime;  
      @Override  
        public void onCreate(Bundle savedInstanceState) {  
          super.onCreate(savedInstanceState);  
          setContentView(R.layout.activity_main);  
          btnStart = (Button)findViewById(R.id.btnStart);  
          btnStop = (Button)findViewById(R.id.btnStop);  
          textViewTime = (TextView)findViewById(R.id.textViewTime);  
          textViewTime.setText("00:03:00");   
          final CounterClass timer = new CounterClass(180000,1000);  
          btnStart.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View v) {  
              timer.start();  
            }  
          });  
          btnStop.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View v) {  
              timer.cancel();  
            }  
          });  
        }  
      @TargetApi(Build.VERSION_CODES.GINGERBREAD)  
      @SuppressLint("NewApi")  
      public class CounterClass extends CountDownTimer {  
           public CounterClass(long millisInFuture, long countDownInterval) {  
                super(millisInFuture, countDownInterval);  
           }  
           @Override  
          public void onFinish() {  
            textViewTime.setText("Completed.");  
          }  
           @SuppressLint("NewApi")  
           @TargetApi(Build.VERSION_CODES.GINGERBREAD)  
           @Override  
           public void onTick(long millisUntilFinished) {  
                 long millis = millisUntilFinished;  
                  String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),  
                      TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),  
                      TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));  
                  System.out.println(hms);  
                  textViewTime.setText(hms);  
           }  
      }  
 }  

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent"  
   android:orientation="vertical" >  
   <Button  
     android:id="@+id/btnStart"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentLeft="true"  
     android:layout_centerVertical="true"  
     android:layout_marginLeft="28dp"  
     android:text="Start" />  
   <Button  
     android:id="@+id/btnStop"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentRight="true"  
     android:layout_centerVertical="true"  
     android:layout_marginRight="67dp"  
     android:text="Stop" />  
   <TextView  
     android:id="@+id/textViewTime"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_above="@+id/btnStop"  
     android:layout_centerHorizontal="true"  
     android:layout_marginBottom="17dp"  
     android:textSize="25sp" />  
 </RelativeLayout>  

Download zip code

Thank you!

21 comments:

  1. hi manish i have some problem in emulator,it shows equal to(=) in google search engine in android emulator and it increases equal to and it doesn't show any output do you have any solution for this plz help me

    ReplyDelete
    Replies
    1. is it working fine on your mobile device? and please try on another emulator may be some problem with emulator setting.

      Delete
  2. Thank you for the code, but how can I increase the amount of minutes and display only minutes and seconds, like: 04.00?

    ReplyDelete
    Replies
    1. long millis = millisUntilFinished;
      Do google how to format mili second to minute.

      Delete
  3. How to get countdown in wallpaper service

    ReplyDelete
  4. I do this to check on my man....

    ReplyDelete
  5. is it possible to use pause and resume function for this timer

    ReplyDelete
    Replies
    1. Yes you can, take a temp variable and on pause store time duration in temp variable and reduce tit from your main timer thread in millisecond.

      Delete
    2. thanks for the reply...sorry im new to android...can you please paste that code...thank you

      Delete
    3. I will update the post on weekend.

      Delete
    4. thank you so much..Ill wait for the update..

      Delete
    5. This comment has been removed by the author.

      Delete
    6. Hi srivastava

      May i know when will you update the post,as i have to implement it in my app.

      Delete
  6. hey Manish srivastava!
    How can i increment the countdown timer. Like if a button is pressed, increment the timer.

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. How to create timer which can run in background?plz help...


    ReplyDelete
    Replies
    1. You can use count down timer-

      private class MyCounter extends CountDownTimer {

      public MyCounter(long millisInFuture, long countDownInterval) {
      super(millisInFuture, countDownInterval);
      // TODO Auto-generated constructor stub
      }

      @Override
      public void onFinish() {
      // TODO Auto-generated method stub
      boolean isLogin=PreferenceConnector.readBoolean(SplashActivity.this, PreferenceConnector.IS_USER_LOGIN, false);
      if(isLogin==true){
      mIntent = new Intent(SplashActivity.this, HomeActivity.class);
      }
      else{
      mIntent = new Intent(SplashActivity.this, AskLoginSignUpActivity.class);
      }
      startActivity(mIntent);
      finish();
      }

      @Override
      public void onTick(long millisUntilFinished) {
      // TODO Auto-generated method stub

      }

      }


      And call it like-
      mCounter = new MyCounter(3000, 1000);
      mCounter.start();

      Delete
  10. When I close the app the counter still continue to finish, which is good. But when I open the app again while counting down the onTick method don't update the new instance of the textView in the UI.
    Is there a way to make this work?

    ReplyDelete
    Replies
    1. I think you delete your application from TASK-LIST right? If no then it should update the Textview no matter it is in background. Well you can use Broadcast Receiver to update your UI thread when your counter finish.

      Delete
  11. Hi manish...thank u for the easy understanding code. Could you guide me how to use the same code if i wanted to make countdown timer as widget instead of app

    ReplyDelete