Anita
Anita

Reputation: 49

how to set a countdown timer for a specific time

I have a class that is taking two time values and finding that a given time interval is present within the time range by using system's current time. Now I want to set a countdown timer which should calculate the time left for a particular time interval. Can anyone show me how to set a countdown timer for calculating the time left for 'exact time' in this code?

// start time
String string1 = date + " 20:30:00";  
Date time1 = new SimpleDateFormat("MM-dd-yyHH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);

// end time
String string2 = date + " 06:30:00";  
Date time2 = new SimpleDateFormat("MM-dd-yy HH:mm:ss").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);

// exact time
String string3 = date + " 04:36:00";
Date F = new SimpleDateFormat("MM-dd-yy HH:mm:ss").parse(string3);
Calendar c3 = Calendar.getInstance();
c3.setTime(F);   

Upvotes: 0

Views: 3128

Answers (1)

Sabin
Sabin

Reputation: 41

You can use a CountDownTimer to do this. Here is a class for CountDownTimer you can implement.

public class MyCountDownTimer extends CountDownTimer {
  public MyCountDownTimer(long millisInFuture, long interval) {
  super(millisInFuture, interval);
  }

  @Override
  public void onFinish() {
    my_textview.setText("Time's up!");     
  }

  @Override
  public void onTick(long millisUntilFinished) {
    my_textview.setText("" + millisUntilFinished / 1000);   //Shows no. of seconds left
    //Uses a textview to update status                                                        
  }
}

You can use this class within your activity. Inside the activity you can implement this

CountDownTimer countDownTimer = new MyCountDownTimer(millisInFuture, interval);
//In this case
//CountDownTimer countDownTimer = new MyCountDownTimer(50000, 1000); 

Here millisInFuture is the "time left for your particular time interval" in milliseconds when you start the timer. Let's say time left is 50 sec in this case. Then this value will be 50000

interval is the time in milliseconds in which you want to provide update. (i.e if you use 1000 as interval, the timer will update you every 1 second)

In this case

onTick(long millisUntilFinished) 

is called every 1 second which gives you time left for the countdown timer in milliseconds.i.e. millisUntilFinished parameter gives you 49000 (i.e. 49 seconds left) when called for the first time and so on.

When the timer has finished countdown, onfinish() is called.

You can show this information in any way. I've simply shown it in a TextView.

The only step left for you is to actually start the countdown timer. countDownTimer.start();

There is a good tutorial on countdown timer here also. http://androidbite.blogspot.com/2012/11/android-count-down-timer-example.html

Upvotes: 1

Related Questions