2017-07-28 77 views
0

我正在製作一個簡單的應用程序,顯示問題,用戶在10秒鐘內應答或點擊下一步,當用戶單擊下一步時,顯示下一個問題,計時器再次變爲10秒。 我使用Asytask處理時間計數器,但是當我點擊下一個按鈕時,顯示下一個問題,但計時器延遲如2秒鐘左右從10開始, 例如: 在屏幕上:問題1是顯示,剩下的時間是8秒。 當我點擊下一步按鈕 問題2顯示,但時間是8然後2或3秒時間到10,並開始遞減: 我的問題是: 有沒有更好的方法來處理這個問題?當接下來的問題則顯示它爲什麼是時間掛像2或3秒鐘,然後從10 這裏重新開始是我的代碼:通過調用AsyncTask對象多次更新UI

// this method is called to reset the timer to 10 and display next 
    question 

    private void displynextquestion(){ 
    // cancel the current thread . 

    decrease_timer.cancel(true);  
    decrease_timer =new Decrease_timer(); 
    // execute again and set the timer to 10 seconds 
    decrease_timer.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,10); 
    // some code 
    } 
    private class Decrease_timer extends AsyncTask <Integer ,Integer,Void>{ 

@Override 
protected Void doInBackground(Integer... integers) { 

    for (int i=integers[0];i>=0;i--){ 
     publishProgress(i); 
     try { 
      Thread.sleep(1000); 

     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 

    return null; 
} 

@Override 
protected void onProgressUpdate(Integer... values) { 
    super.onProgressUpdate(values); 
    timeview.setText(""+values[0]); 
} 

} }

回答

0

使用CountDownTimer,是更容易:

CountDownTimer countDownTimer = new CountDownTimer(10000, 1000) { 

    public void onTick(long millisUntilFinished) { 
     mTextField.setText("seconds remaining: " + millisUntilFinished/1000); 
    } 

    public void onFinish() { 
     mTextField.setText("done!"); 
    } 
}; 

在CountDownTimer構造第一個參數是在毫秒的總時間,和第二個參數是沿着接收onTick(長)的回調的方式間隔。

要重新啓動,只要致電:

countDownTimer.cancel(); 
countDownTimer.start(); 

見多https://developer.android.com/reference/android/os/CountDownTimer.html

+0

它的工作好感謝 –