2010-09-05 87 views
1

我發現Android的定時器此代碼, 公共類myActivity延伸活動{Android的計時器問題

private Timer myTimer; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 
    setContentView(R.layout.main); 

    myTimer = new Timer(); 
    myTimer.schedule(new TimerTask() { 
     @Override 
     public void run() { 
      TimerMethod(); 
     } 

    }, 0, 1000); 
} 

private void TimerMethod() 
{ 
    //This method is called directly by the timer 
    //and runs in the same thread as the timer. 

    //We call the method that will work with the UI 
    //through the runOnUiThread method. 
    this.runOnUiThread(Timer_Tick); 
} 

private Runnable Timer_Tick = new Runnable() { 
    public void run() { 

    //This method runs in the same thread as the UI.    

    //Do something to the UI thread here 

    } 
}; 

} 我需要了解一件事...評論說,這種方法在同一個線程中運行就像Ui一樣,這意味着即使在屏幕關閉或活動被推到背景時,這種方法也會繼續運行,例如,在打來電話的情況下?

回答

0

不,這一切意味着特定的方法與THAT ACTIVITY的UI在相同的線程環境中運行。

意思是說,它會按預期在後臺運行。 (只要你的活動正在運行,這並不總是一個保證,即如果用戶按下回家或啓動任何其他應用程序的操作系統可以隨時殺死你的活動

所以,如果你有一個電話,或屏幕變暗特定的代碼將能夠通過之類的東西烤麪包,或者其活性UI修改UI。

至少在理論上,它不會傷害到自己的實際測試這些東西。