2014-12-04 49 views
2

我一直在試圖創建一個代碼,將倒計時到聖誕節的android應用程序。如何創建聖誕倒計時

這是我到目前爲止。

 Calendar thatDay = Calendar.getInstance(); 
     thatDay.setTime(new Date(0)); /* reset */ 
     thatDay.set(Calendar.DAY_OF_MONTH, 25); 
     thatDay.set(Calendar.MONTH, 11); // 0-11 so 1 less 
     thatDay.set(Calendar.YEAR, 2014); 

     Calendar today = Calendar.getInstance(); 


    while (true) 
    { 


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

    long days = diffSec/SECONDS_IN_A_DAY; 
    long secondsDay = diffSec % SECONDS_IN_A_DAY; 
    long seconds = secondsDay % 60; 
    long minutes = (secondsDay/60) % 60; 
    long hours = (secondsDay/3600); // % 24 not needed 

    } 

但是,當我嘗試循環它時,它會產生太多的輸出。我怎樣才能每秒顯示代碼更新?

請幫忙!!

回答

1

如果使用ScheduledExecutorService的,其重複,直到它到達目的地時最好。 它的優點是它不會在打印輸出之間使用處理器時間。

final ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1); 
    final Calendar thatDay = new GregorianCalendar(2014, 11, 25); 
    final Calendar today = Calendar.getInstance(); 
    service.schedule(new Runnable() { 

     @Override 
     public void run() { 
      long diff = thatDay.getTimeInMillis() - today.getTimeInMillis(); 
      long diffSec = diff/1000; 
      long days = diffSec/SECONDS_IN_A_DAY; 
      long secondsDay = diffSec % SECONDS_IN_A_DAY; 
      long seconds = secondsDay % 60; 
      long minutes = (secondsDay/60) % 60; 
      long hours = (secondsDay/3600); // % 24 not needed 
      if (diff > 0) { 
       ses2.schedule(this, 1, TimeUnit.SECONDS); 
      } 
     } 
    }, 1, TimeUnit.SECONDS); 
1

你的循環

while (true) { 
    ... 
} 

永遠不會終止,因爲你在它沒有break;

相反,嘗試for循環:

import java.text.SimpleDateFormat; 
import java.util.concurrent.TimeUnit; 

SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd"); 
Date xmas = f.parse("2014-12-25"); 
for (long i = System.currentTimeMillis(); i < xmas.getTime(); i += TimeUnit.HOURS.toMillis(1)) { 
    long hours = TimeUnit.MILLISECONDS.toHours(xmas.getTime() - i); 
    // do something with hours 
} 

該循環由小時,直到聖誕節,但你可以改變這種狀況很容易。

請注意使用TimeUnit類,而不是大量的數學線。

+1

甚至在聖誕節之後;) – rzysia 2014-12-04 14:54:04

+0

小錯字,'i Compass 2014-12-04 15:01:42

+0

@compass是的,當我在iPhone上使用縮略圖代碼時,我有些錯誤。固定,thx。 – Bohemian 2014-12-04 15:07:32