0

I get a project start time from a web service and work out the time the project had taken up to the current date. I store the datetime I get from the web in the startTimeList.

Here is how I'm getting the current elapsed time on the project:

public void setTimeElapsed() {
    try {
        Calendar calStart = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        calStart.setTime(sdf.parse(startTimeList.get(0)));

        long startMillis = calStart.getTimeInMillis();

        long now = System.currentTimeMillis();
        long difference = now - startMillis;

        Calendar calDiff = Calendar.getInstance();
        calDiff.setTimeInMillis(difference);

        int eYear = calDiff.get(Calendar.YEAR);
        int eMonth = calDiff.get(Calendar.MONTH);
        int eDay = calDiff.get(Calendar.DAY_OF_MONTH);
        int eHour = calDiff.get(Calendar.HOUR_OF_DAY);
        int eMin = calDiff.get(Calendar.MINUTE);
        int eSec = calDiff.get(Calendar.SECOND);

        mimDuration.setText(String.format("%d Months %d Days %d:%d:%d", eMonth, eDay, eHour, eMin, eSec));


    } catch (ParseException e) {
        Log.e(TAG, "Error: " + e.getMessage());
    }
}

However this does not keep updating the elapsed time for the user to see the real time. I need to add a handler (timer) of some sorts to keep updating the time on the UI.

Any help would be appreciated. Thank you.

Anro Swart
  • 95
  • 1
  • 12

1 Answers1

1

You can create a timerTask and use a timer to schedule it periodically. Inside the run method you can update the ui by either using runOnUiThread method or a handler.

So something like

timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            Long spentTime = System.currentTimeMillis() - startTime;

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                }
            });

        }
    },0, interval);
Smit Davda
  • 638
  • 5
  • 15