2010-09-06 38 views
0

我使用這個代碼:當我運行它,我在logcat中得到這個例外Android的定時器處理

public class newtimer extends Activity { 

    private Timer myTimer; 

    @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); 
    } 

    int number = 0; 

    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. 

     Toast.makeText(this, "TimerMethod Running "+number, Toast.LENGTH_SHORT).show(); 

     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 

      Toast.makeText(getBaseContext(), "UI Thread Running "+number, Toast.LENGTH_SHORT).show(); 

     } 
    }; 
} 

09-06 21:39:39.701:ERROR/AndroidRuntime(1433 ):了java.lang.RuntimeException:無法內螺紋創建處理程序尚未調用Looper.prepare()

+0

該代碼完全沒有格式化。發佈問題前請先看預覽。 – EboMike 2010-09-06 16:37:02

回答

0

我將承擔的問題是在你的TimerMethod功能Toast.makeText(this, "TimerMethod Running "+number, Toast.LENGTH_SHORT).show(); - 你不能從工作線程調用與UI有關的任何函數。由於在UI線程中運行的部分中已經有了Toast,爲什麼TimerMethod中還有另一個?

對於調試,我建議儘可能使用日誌而不是吐司。