2016-06-21 76 views
0

我想提出一個簡單的應用程序,它使用倒計時定時器,循環 進度條和3個按鈕開始,暫停和Resume.What我想 做的就是當一個特定的活動開始,我按下暫停存儲 計時器暫停並從該點繼續前進的時間 forward.But問題是倒計時timmer不停止,因此如果我在7秒暫停7秒進度條停止在7秒,但當我按 恢復它從倒數計時器的值在那個時刻開始。這是我試圖實現的代碼。在Android中暫停和恢復倒數計時器和進度條?

btnPause.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       //When user request to pause the CountDownTimer 
       isPaused = true; 

       //Enable the resume and cancel button 
       btnResume.setEnabled(true); 
       //Disable the start and pause button 
       btnStart.setEnabled(false); 
       btnPause.setEnabled(false); 
      } 
     }); 



btnResume.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     //Disable the start and resume button 

     btnStart.setEnabled(false); 
     btnResume.setEnabled(false); 
     //Enable the pause and cancel button 
     btnPause.setEnabled(true); 

     //Specify the current state is not paused and canceled. 
     isPaused = false; 
     isCanceled = false; 
     mCountDownTimer.start(); 
} 
    }); 

這對於倒數計時器代碼。

private void neck_rotations() 
    { 
     neckRotation = true; 
     mCountDownTimer = new CountDownTimer(NECK_ROTATION_TIME, 1000) 
     { 
      @Override 
      public void onTick(long millisUntilFinished) 
      { 

       if (isPaused || isCanceled) 
       { 
        paused_at = (int) (millisUntilFinished/1000); 

       } else 
       { 
        timeRemaining = (int) (millisUntilFinished/1000); 
        donutProgress.setMaxValue(NECK_ROTATION_TIME/1000); 
        donutProgress.setValueAnimated((int) timeRemaining); 
        counter.setText(String.valueOf(timeRemaining)); 

       } 

      } 

      @Override 
      public void onFinish() 
      { 
       response = "Jumps"; 
       rest(response); 

      } 
     }; 
     mCountDownTimer.start(); 
    } 

我是新手編程,所以任何幫助或建議表示讚賞。謝謝。

回答

1

請參閱本:

How to clear CountDownTimer from onTick method?

我不知道你可以從仍然從內部onTick()方法倒計時關閉計時器。

爲CountDownTimer創建一個gloabl引用,並僅從該引用上的clickListeners調用start()或cancel()。

+0

是的我已經倒計時器global.I使用相同的倒數計時器爲3種不同的方法.neck_rotation(),hand_rotation()和跳轉(),所以當用戶點擊開始第一個方法被調用和開每種方法完成後都有10秒的休息時間。 – AndroidNewBee

+0

就像我看到的那樣,當您按btnResume時您正在創建一個新的CountDownTimer,並且您還將mCountDownTimer作爲另一個CountDownTimer的引用。這是爲什麼 ?繼續使用onClick()的mCountDownTimer。無論如何,不​​應該在onTick()函數中調用cancel()函數。 – Gil

+0

是的,你可以幫助嗎?你可以舉一個例子或什麼? – AndroidNewBee