Inaccurate CountDownTimer results for Java/Android
===

I currently have a simple timer activity where a user can select a start time and I use the CountDownTimer class to count down to 0 from the specified start time. There is also a little bit of extra processing done to format the time remaining on the screen to the way I want it, which is where I am getting the inaccurate results. I have found that this extra processing can cause a delay of anywhere between 7 and 50 milliseconds.

The CountDownTimer class works as follows: You specify a total time (in milliseconds) and an interval time (1000 ms, or 1 tick per second). With every tick, the screen will reflect to show that a second has passed. However, this processing can take some extra time, meaning some ticks may be "missed" if you are expecting it to hit every 1000 ms.

So, I'm aware that my problem is that I have some processes that take some amount of time (which is not a constant amount of time... It is a range from 7-50ms from a few test runs). I am unsure of how to solve this problem.

My quick, incorrect fix is below... I set a threshold for each tick (so, between 1050 and 950ms since the last tick). This is not a good method as it does not catch every tick... It just catches *more* ticks. I could use some help coming up with a more bulletproof solution.

My code:

    public void onTick(long millisUntilFinished) {
	    	
	    	System.out.println(millisUntilFinished); //Keeping track of change in MS
	    	String message2, message3;
	    	if (millisUntilFinished >= 1000){ //Still more than 1 sec remaining
                
                //The following if statement sees if the tick falls into the threshold
	    		if (millisUntilFinished % 1000 < 50 || millisUntilFinished > 950){

	    			//format logic below
                                if (S == 0){        
	    				S = 59;
	    				if (M == 0 && H > 0){
	    					M = 59;
	    					H--;
	    				}
	    				else {
	    					M--;
	    				}
	    				
	    			}
	    			else {
	    				S--;
	    			}
	    		}
	    	}
	    	else{
                //Less than 1 sec remaining
	    		try{
                      //Sleep for the remaining amount of time left... Then end the timer.
	    			Thread.sleep(1000-millisUntilFinished);
	    			S--;
	    		}
	    		catch(InterruptedException ie){
	    			
	    		}
	    	}