2016-03-11 90 views
1

我有android自動啓動倒數計時器。我需要暫停並繼續。我見過其他解決方案,但他們沒有工作。我的代碼是:暫停和恢復android倒數計時器

class Timer extends CountDownTimer 
{ 
    public Timer(long millisInFuture, long countDownInterval) 
    { 
     super(millisInFuture, countDownInterval); 
     timerTimedOut = false; 
    } 

    @Override 
    public void onFinish() { 
     if(timerTimedOut){ 
      doSTH(); 
     } else { 
      doSTHElse(); 
     } 

     this.start(); 
    } 

    @Override 
    public void onTick(long millisUntilFinished) 
    { 
     timerShow.setText(Long.toString(millisUntilFinished/1000)); 

    } 
    public void stop(){ 
     timerTimedOut = true; 
     this.cancel(); 
     onFinish(); 
    } 
} 

我該怎麼做才能暫停和恢復?

+1

這已經[回答](http://stackoverflow.com/q/5738362/5598783)之前。 –

回答

2

我一直在處理這個問題,在嘗試了很多事情之後,我發現了這個解決方案。在這裏,您可以找到Android CountDownTimer類的很好選擇: https://gist.github.com/bverc/1492672

您只需創建一個名爲CountDownTimer2的新類,然後粘貼該代碼即可。然後,用它來代替正常的CountDownTimer類,例如:

CountDownTimer2 cdt = new CountDownTimer2(30000, 1000) { 
     @Override 
     public void onTick(long millisUntilFinished) { 

      //Whatever you want to do onTick 


     } 

     @Override 
     public void onFinish() { 
      Log.i(TAG, "Timer finished"); 
     } 


    }; 

    cdt.start(); 

} 

的,那麼你只需要通過

cdt.pause(); 

cdt.resume(); 

希望它能幫助。