2010-09-05 70 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。

至少在理论上,它不会伤害到自己的实际测试这些东西。