2014-12-06 63 views
0

我一直在爲一個應用程序的代碼工作,但當我運行代碼時,我無法在模擬器中得到更新的時間。該代碼在編譯器中運行,但不在仿真器中運行。 任何有幫助的建議將不勝感激。計時器是聖誕節倒計時。 這裏是我的代碼:如何在Java模擬器中每秒更新一次?

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

回答

0

保持的東西很簡單,我會刪除所有執行人的東西,這樣做:

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); 
0

還有一點點加到rupps的答案。您可以使用

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

簡化數學和給予更多的用戶可讀的字符串用戶。

相關問題