How to update time every second in Java emulator?

2019-09-02 15:34发布

问题:

This question already has an answer here:

  • Update time every second 3 answers

I have been working on a code for an app but I cannot get the time to update in the emulator when I run the code. The code works in the compiler but not the emulator. Any helpful suggestions would be greatly appreciated. The timer is a countdown to Christmas day. Here is my code:

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;

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

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

回答1:

Keeping things very simple, I'd remove all Executors stuff and do something like:

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

// We create a runnable that will re-call itself each second to update time
Runnable printDaysToXmas=new Runnable() {

   @Override
   public void run() {
      Calendar today = Calendar.getInstance();
      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.setText(" + "" + days + "" + hours + "" + minutes + " " + seconds + " ");

      // we call this runnable again in 1000ms (1 sec)
      daysBox.postDelayed(printDaysToXmas, 1000); // all views have a Handler you can use ;P
   }
};

... and to start the process just do

printDaysToXmas.run();

... and to stop it, you can do

daysBox.removeCallbacks(printDaysToXmas);


回答2:

Also some little add to rupps answer. You can use

DateUtils.getRelativeTimeSpanString(long time, long now, long minResolution);

to simplify math and give more user readable string for user.