2011-11-26 135 views
2

好的,我需要在倒數時創建一個無限循環。我的代碼是:如何創建無限循環

public void countdown() { 
    if (x != null) { 
     x.cancel(); 
    } 

    x = new CountDownTimer(20000, 1000) { 
     public void onTick(long millisUntilFinished) { 
     } 

     public void onFinish() { 
      showNotification(); 
     } 
    }; 
    x.start(); 
} 

x只是一個靜態的countdowntimer變量。問題是我嘗試了很多方法來使上面的代碼工作,我的意思是倒計時結束時,它顯示通知,它應該重新開始,等等......但我找不到辦法做到這一點。

回答

1

你可以只使用一個while循環:
while (true) {
// do stuff
}

當它做的「東西」,它西港島線重新開始,無限!

+0

這不會重新啓動CountDownTimer,但它會instanciate和無限期地啓動一個計時器的掠奪,這不是什麼人想要:) – Houcine

+0

CPU使用很多這種方法,需要使用asynctask –

8

希望這會對你有所幫助。

public void countdown(){ 
    if (x != null) { 
     x.cancel(); 
    } 
    x = new CountDownTimer(20000, 1000) { 
     public void onTick(long millisUntilFinished) { 
     } 
     public void onFinish() { 
      showNotification(); 
      x.start(); 
     } 
    }; 
} 
+0

你解決了這個問題嗎? ? – freshDroid

4

是當他已經完成重新啓動定時器:) 這樣的:

x = new CountDownTimer(20000, 1000) { 
      public void onTick(long millisUntilFinished) { 
      } 

      public void onFinish() { 
       showNotification(); 
       start();// here, when your CountDownTimer has finished , we start it again :) 
      } 
     }; 
     x.start(); 
2

爲什麼不使用常規的計時器?它會重複上一個指定的時間間隔,直到調用取消(),是這樣的:

public void countdown() { 
    if (x != null) { 
     x.cancel(); 
    } 

    x = new Timer("timerName"); 
    x.schedule(_timerTask, 0, 20000); 
} 

private static final TimerTask _timerTask = new TimerTask() { 
    @Override 
    public void run() { 
     showNotification(); 
    } 
}; 
1

,讓您的計時器的工作只是把

<countdowntime>.start(); 

onfinish

+0

this.start();;; –

1

爲了記錄CountDownTimer (long millisInFuture,long countDownInterval)

// A not so infinite but close to infinte interval for each second 
    CountDownTimer cdt=new CountDownTimer(Long.MAX_VALUE, 1000) { .... } 

其中Long.MAX_VALUE = 9223372036854775807毫秒或年左右2.92億(秒或多或少)

它不是無限的,但其令人難以置信的長。