Search code examples
androidtimercountdown

countdowntimer skipping some milliseconds


as you can see the last call onTick is happening with 2 seconds, then the next call is nearly 2 seconds later.

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

tv = new TextView(this);
this.setContentView(tv);
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss:SSS");
formatter.setLenient(false);


newTime = "31.12.2015, 23:59:59:999";

try {
    newDate = formatter.parse(newTime);
    milliseconds = newDate.getTime();


    currentTime = System.nanoTime();

    diff = milliseconds - currentTime;


} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

MyCount counter = new MyCount(milliseconds, 1000);
counter.start();


}

CountDownTimer

public class MyCount extends CountDownTimer {
    public MyCount(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onFinish() {
    }

    @Override
    public void onTick(long millisUntilFinished) {
        serverUptimeSeconds = (millisUntilFinished - System
                .currentTimeMillis()) / 1000;
        String serverUptimeText = String.format(
                "%d days %d hours %d minutes %d seconds",
                serverUptimeSeconds / 86400,
                (serverUptimeSeconds % 86400) / 3600,
                ((serverUptimeSeconds % 86400) % 3600) / 60,
                ((serverUptimeSeconds % 86400) % 3600) % 60);
        tv.setText(serverUptimeText);
    }
}

Output:

10 seconds 
8 seconds 
6 seconds 
4 seconds 

P.S ~ check video for more info

https://www.dropbox.com/s/7b3hme5ekdqpfi1/79789789.avi?dl=0


Solution

  • Try this out :

    TimerTask runTimerTask = new TimerTask() {
        @Override
        public void run() {
            // your code
        });
    };
    
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(runTimerTask, 0, 500);