Sunday, 13 November 2016

CountDown Timer in Android




A countdown timer is a device which is designed to count down to a particular event. They range in design from simple mechanical devices like those used in the kitchen to electronic versions designed to be downloaded and installed on a desktop. Numerous websites also use a countdown timer to mark the days, hours, minutes, and seconds until a major event, and some websites also generate countdown timer codes for installation on personal websites.

I am going to share the logic of designing a countdown timer in Android. Designing the countdown timer is not so difficult. The below code will create a countdown timer for 5 minutes.


void TimerStart(long remainingTime) {
CountDownTimer myTimer= new CountDownTimer(300000, 1000) {
// adjust the milli seconds here
public void onTick(long millisUntilFinished) {
text1.setText(""+String.format(FORMAT,
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)))); }
public void onFinish() {
text1.setText("done!"); } };
myTimer.start();
}



But if I closed my app after using it for 30 seconds and reopen it after 2 minutes, it will start it’s countdown from 5 minutes. Ideally, it should subtract the time elapsed since I reopen the app. How to handle this ?? Well, Don’t worry !...I have a solution.


Let's take an example of running the countdown Timer for 24 hours.

Step 1 :  Calculate the timerEndTime(in milliseconds), i.e when the timer is going  to stop. You can do this by adding 86400000(number of milliseconds in 24 hours)  to the starting time of the countdownTimer.

Step 2 : Calculate the currentTime(in milliseconds)   i.e when you open the      application. You can do this by using the method called,    Calendar.getInstance().getTimeInMillis() 

Step 3 : Calculate the remaining time to the countdown timer by
             (timerEndTime – currentTime)

Step 4: Pass this value to the countDownTimer method
i.e TimerStart(timerEndTime - currentTime)

You are Done !!! 

Please comment below if you face any problem in the implementation of the above-discussed steps. 

No comments:

Post a Comment