2012-04-13 15 views
0

我有一個TimerTask在Android的一個問題,我有這樣的代碼:如何更改android中的新TimerTask動作?

timer = new Timer(); 
timer.schedule(new TimerTask() { 
     public void run() { 
      countInt = countInt + 1; 
      textview1.setText(countInt); 
     } 
    }, 1000); 

定時任務獲得startet我的應用程序崩潰每一次,我的事情,因爲我訪問TextView的,它是在其他線程權利?

如何解決這個問題?

回答

3

試試這個..

timer = new Timer(); 
    timer.schedule(new TimerTask() { 
      public void run() { 
       countInt = countInt + 1; 
       yourActivity.this.runOnUiThread(new Runnable() 
       public void run(){ 
        {textview1.setText(String.valueOf(countInt))}); 
       } 
      } 
     }, 1000); 

它崩潰,因爲你是用屬於這是不允許的UI線程的東西搞亂(textview1.setText(countInt);) ......

4

是的,你是對的,它崩潰的原因」你正在從不是UI線程訪問視圖。爲了解決這個問題,你可以使用你的活動發佈一個Runnable到UI線程

timer = new Timer(); 
timer.schedule(new TimerTask() { 
    public void run() { 
     countInt = countInt + 1; 
     YourActivity.this.runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       textview1.setText(countInt); 
      } 
     }); 
    } 
}, 1000); 
相關問題