如何在Java模拟器中每秒更新一次?

时间:2014-12-06 02:38:51

标签: java android android-emulator

我一直在为应用程序编写代码,但在运行代码时,我无法在模拟器中获得更新时间。代码在编译器中工作,但不在仿真器中工作。 任何有用的建议将不胜感激。计时器是圣诞节的倒计时。 这是我的代码:

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 + " ");

2 个答案:

答案 0 :(得分:0)

保持简单,我将删除所有Executors的东西并执行以下操作:

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
   }
};

...并开始这个过程

printDaysToXmas.run();

...并且要停止它,你可以做到

daysBox.removeCallbacks(printDaysToXmas);

答案 1 :(得分:0)

还有一点点添加rupps答案。你可以使用

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

简化数学运算并为用户提供更多用户可读的字符串。