Monday, June 4, 2012

Long Countdown Timer for Android

I will be showing you how to create a long countdown timer for Google Android development.

Place this in your onCreate method for the activity with the countdown. In your layout, create a TextView and give it an id of 'txtTimer'.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Date date = new Date(115,4,26,12,0,0);
        long dtMili = System.currentTimeMillis();
        Date dateNow = new Date(dtMili);
        long remain = date.getTime() - dateNow.getTime();

        new CountDownTimer(remain, 1000)
        {
            @Override
            public void onFinish()
            {
                //Action for when the timer has finished.
                TextView tv = (TextView) findViewById(R.id.txtTimer);
                tv.setText("Timer has Finished");
            }

            @Override
            public void onTick(long millisUntilFinished)
            {
                //Action for every tick of the countdown.
                TextView tv = (TextView)findViewById(R.id.txtTimer);
                tv.setText(timeCalculate(millisUntilFinished/1000) + " Countdown");
            }
        }.start();
    }  


First off we need to implement Androids CountDownTimer. The first parameter is the amount of milliseconds it will take to finish and the second parameter is the interval to countdown at (1000 represents 1 second).


Set the variable 'date' to the Date you want the countdown to end at. Keep in mind Java starts at year 1900, the month January starts at 0 and the hours are military time. In the following example I'm making a countdown to May 26, 2012 at 12PM.




Next, I created a separate method that converts long milliseconds into a string output. Credit to the Stack Overflow question for the following code. http://stackoverflow.com/questions/3749297/countdown-timer-in-android
   public String timeCalculate(long ttime)   
   {  
     long days, hours, minutes, seconds;  
     String daysT = "", restT = "";  
   
     days = (Math.round(ttime) / 86400);  
     hours = (Math.round(ttime) / 3600) - (days * 24);  
     minutes = (Math.round(ttime) / 60) - (days * 1440) - (hours * 60);  
     seconds = Math.round(ttime) % 60;  
   
     if(days==1) daysT = String.format("%d day ", days);  
     if(days>1) daysT = String.format("%d days ", days);  
   
     restT = String.format("%02d:%02d:%02d", hours, minutes, seconds);  
   
     return daysT + restT;  
   }