2011-09-29 205 views
0

經過多次解決方案的試用(包括在SO上發佈問題),我會努力工作。但沒有改善。回到我的問題,我正在實施一個有倒數計時器的應用程序。我在一個按鈕上顯示了它(通過禁用點擊事件就像使用畫布一樣)。 當用戶點擊一個按鈕(這是一個單獨的按鈕)時,我啓動計時器。下面是倒計時代碼,線程執行延遲+ Android

public class DigitalTimer extends Button{ 

--------------------------------  
--------------------------------  
--------------------------------  
--------------------------------  
--------------------------------  
--------------------------------  
private String timerText; 
public DigitalTimer (Context context,int hourstime,int mintime,int sectime){ 
    super(context); 
    Log.d(TAG,"DigiTimer constructor");  
    this.context = context;  
    initialize(hourstime,mintime,sectime,timerType); 
    setClickable(false); 
} 

public void initialize(int hourstime,int mintime,int sectime,int timerType){ 
    Log.d(TAG,"DigiTimer initialize");  
    this.hourstime = hourstime; 
    this.mintime = mintime;  
    hour = hourstime; 
    min = mintime; 
    sec = sectime; 

    //Just Thread version    
    **digiThread = new Thread(){ 
     @Override 
     public void run(){ 
      while(!isPauseTimer()){ 
       updateTimes(); 
       SystemClock.sleep(UPDATEDELAY); 
      } 

     }   
    };** 


    //Handler version  

    /* 
    handleRunnable = new Runnable(){ 
     public void run(){ 
      updateTimes(); 
     } 
    }; 
    */ 

} 

private void updateTimes(){ 

    timerText = String.format(timerFormat,hour,min,sec);  
    postInvalidate(); 
    sec--; 
    if(sec < 0){ 
     sec = 59; 
     min--; 
    } 
    if(min < 0){ 
     min = 59; 
     hour--; 
    } 

    if(hour < 0){ //when hour is negative it means the given time completed so we stop the timer & alarm permanantely 
    hour = 0; 
    min = 0; 
    sec = 0; 
      } 

} 
@Override 
protected void onDraw(Canvas canvas){ 
    super.onDraw(canvas); 
    Log.d(TAG,"DigiTimer onDraw");  
    setBackgroundResource(R.drawable.button9patch);  
    setText(timerText);  
} 
public void startUpdateTheread(){ 
    //digiHandler.postDelayed(handleRunnable, UPDATEDELAY); 
    **digiThread.start();** 
} 


private void startTimersAndAlarms(){ 
----------------------- 
----------------------- 
----------------------- 
----------------------- 
**startUpdateTheread();** 
--------------------- 
--------------------- 

} 

}

最初定時器沃金罰款。 但是如果倒計時的時間沒有更高(比如說5:00:00),那麼它的運行會很好,直到某個時候(比如說4:00:00),它會延遲計時器更新。 (只需倒計時一分鐘就會花費更多時間......特別是當用戶不在應用程序中時) 首先,我嘗試使用處理程序。我遇到了問題。我認爲延遲是因爲保持UI線程繁忙。所以我開發了一個單獨的線程。但問題仍然存在。

對不起,很長的文章。請有人指出發生了什麼事。那是我遺失的東西還是把代碼放在錯誤的地方?

感謝

編輯:我讀SystemClock.sleep文檔。它說:「{當系統進入深度睡眠(CPU關閉,顯示黑暗,設備等待外部輸入)時,此時鐘停止}」。我明白我應該在運行此線程時保持CPU處於開啓狀態。所以根據@Brandon的回答,我應該實現部分POWERLOCK以保持CPU處於開啓狀態。我的理解是否正確?

回答

1

如果你想有一個準確的計時器,我想你需要得到一個喚醒鎖。

退房的PowerManager

的文檔,你可以得到一個FULL_WAKE_LOCK保持在屏幕上,或PARTIAL_WAKE_LOCK保持CPU的運行。不要忘記將權限添加到您的AndroidManifest文件中。

+0

感謝您的回答。是。我已經實現了喚醒鎖來保持屏幕開啓。這是工作。但我的問題是當用戶退出App時管理倒數計時器。即當用戶退回到應用程序時,如果用戶退出(主頁或後退按鈕)應用程序,當計時器顯示03:30:00 ... 1分鐘後,應該顯示03:31:00。它也顯示了這一點,但有時延遲了一段時間。 – droidsites

+0

請看我的編輯 – droidsites