如何在Java emulator中每秒更新时间?
我一直在为一个应用程序编写代码,但在运行代码时,我没有时间在模拟器中进行更新。代码在编译器中工作,但在仿真器中不工作。 如有任何有益的建议,将不胜感激。计时器是圣诞节的倒计时。 这是我的密码:如何在Java emulator中每秒更新时间?,java,android,android-emulator,Java,Android,Android Emulator,我一直在为一个应用程序编写代码,但在运行代码时,我没有时间在模拟器中进行更新。代码在编译器中工作,但在仿真器中不工作。 如有任何有益的建议,将不胜感激。计时器是圣诞节的倒计时。 这是我的密码: Calendar today = Calendar.getInstance(); Calendar thatDay = Calendar.getInstance(); thatDay.set(Calendar.DAY_OF_MONTH, 25); thatDay.set(Calendar.MONTH, 1
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 + " ");
让事情变得非常简单,我会删除所有遗嘱执行人的东西,然后做一些类似的事情:
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);
还有一些小补充来回答。你可以用
DateUtils.getRelativeTimeSpanStringlong time,long now,long minResolution
简化数学,为用户提供更多用户可读的字符串