Update time every second

…衆ロ難τιáo~ 提交于 2020-01-07 08:28:10

问题


I need to update time every second on a countdown timer which counts down to Christmas. How do I update the time in my text view.I do not have the code in the onCreate method.

here is some of my code. When I run the code it gives the exact time, but it does not countdown live on screen. Any ideas? Edit: the readThisPeriod is for calculating the time left until Christmas.

  public void DateCalculator() {
      Calendar today = Calendar.getInstance();
      Calendar thatDay = Calendar.getInstance();
      thatDay.set(Calendar.DAY_OF_MONTH, 25);
      thatDay.set(Calendar.MONTH, 11); // 0-11 so 1 less
      thatDay.set(Calendar.YEAR, 2014);
      thatDay.set(Calendar.HOUR, 0);
      thatDay.set(Calendar.MINUTE, 0);
      thatDay.set(Calendar.SECOND, 0);
      thatDay.set(Calendar.AM_PM, 0);
      System.out.println(thatDay.getTime());
      ScheduledExecutorService scheduledExecutorService = 

      Executors.newScheduledThreadPool(1);
      scheduledExecutorService.scheduleAtFixedRate(new ReadThisPeriod(thatDay), 0, 1, 
      TimeUnit.SECONDS);

      long diff = (thatDay.getTimeInMillis() - today.getTimeInMillis()) / 1000;
      long days = diff / (60 * 60 * 24);
      long hours = diff / (60 * 60) % 24;
      long minutes = diff / 60 % 60;
      long seconds = diff % 60;

      daysBox = (TextView) findViewById(R.id.s1Days);


      daysBox.setText("" + "" + days + "" + hours + "" + minutes + "" + seconds + " );
}

回答1:


import android.app.Activity;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import java.util.Calendar;


public class MainActivity extends Activity {

    private TextView daysBox;
    private boolean running;
    private Calendar thatDay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        daysBox = (TextView) findViewById(R.id.main_day);

        thatDay = Calendar.getInstance();
        thatDay.set(Calendar.DAY_OF_MONTH, 25);
        thatDay.set(Calendar.MONTH, 11); // 0-11 so 1 less
        thatDay.set(Calendar.YEAR, 2014);
        thatDay.set(Calendar.HOUR, 0);
        thatDay.set(Calendar.MINUTE, 0);
        thatDay.set(Calendar.SECOND, 0);
        thatDay.set(Calendar.AM_PM, 0);

        startDateCalculator();
    }

    protected void onPause() {
        super.onPause();
        running = false;
    }

    protected void onResume() {
        super.onResume();
        running = true;
    }


    private class CountdownTask extends AsyncTask<Void, Void, Void> {
        protected Void doInBackground(Void... args) {
            while (running) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {

                }

                publishProgress();
            }
            return null;
        }

        protected void onProgressUpdate(Void... res) {
            super.onProgressUpdate(res);

            long diff = (thatDay.getTimeInMillis() - System.currentTimeMillis()) / 1000;
            long days = diff / (60 * 60 * 24);
            long hours = diff / (60 * 60) % 24;
            long minutes = diff / 60 % 60;
            long seconds = diff % 60;


            daysBox.setText("" + "" + days + "d " + hours + ":" + minutes + ":" + seconds + " ");
        }
    }

    public void startDateCalculator() {

        new CountdownTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
}



回答2:


Start a CountDownTimer :

long endTime = thatDay.getTimeInMillis();
new MyCountDownTimer(endTime-System.currentTimeMillis(),1000).start();

Here you go:

public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
  super(startTime, interval);
}
@Override
public void onFinish() {
  textView.setText("Happy Christmas!");
}
@Override
public void onTick(long millis) {
  int SECOND = 1000;
  int MINUTE = 60 * SECOND;
  int HOUR = 60 * MINUTE;
  int DAY = 24 * HOUR;
  StringBuffer text = new StringBuffer();
  if (millis > DAY) {
    text.append(millis / DAY).append(" days ");
    millis %= DAY;
  }
  if (millis > HOUR) {
    text.append(millis / HOUR).append(" hours ");
    millis %= HOUR;
  }
  if (millis > MINUTE) {
    text.append(millis / MINUTE).append(" minutes ");
    millis %= MINUTE;
  }
  if (millis > SECOND) {
    text.append(millis / SECOND).append(" seconds ");
    millis %= SECOND;
  }
  textView.setText(text);
}

}




回答3:


  long diff = (thatDay.getTimeInMillis() - today.getTimeInMillis()) / 1000;
  long total=diff;

            mTimer=new CountDownTimer(total, 1000) {

                 public void onTick(long millisUntilFinished) {
                    diff--;  
                    daysBox.setText(convertSecondToHHMMString(diff));
                 }

                public void onFinish() {
                    System.out.println("Happy Chrismas");

                 }
              }.start();


  private String convertSecondToHHMMString(long secondtTime){

     TimeZone tz = TimeZone.getTimeZone("UTC");
     SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
     df.setTimeZone(tz);
     String time = df.format(new Date(secondtTime*1000L));

     return time;
 }


来源:https://stackoverflow.com/questions/27333329/update-time-every-second

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!