2012-06-27 72 views
2

我正在使用Eclipse for Android。我試圖做一個簡單的重複計時器,它有一個很短的延遲。 它將在單擊TextView timerTV後啓動。此代碼是在onCreate方法:如何設置實際可用的Timer.scheduleAtFixedRate()?

timerTV = (TextView) findViewById(R.id.timerTV); 
    timerTV.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

       Timer gameTimer = new Timer(); 
       TimerTask doThis; 

       int delay = 5000; // delay for 5 sec. 
       int period = 1000; // repeat every sec. 
       doThis = new TimerTask() { 
       public void run() { 
           Toast.makeText(getApplicationContext(), "timer is running", Toast.LENGTH_SHORT).show(); 
       } 
       }; 
       gameTimer.scheduleAtFixedRate(doThis, delay, period); 

每次我嘗試運行它,一個「類文件編輯器」與錯誤彈出: 「源未找到」 JAR文件C:\ Program Files文件\ Android \ android-sdk \ platforms \ android-8 \ android.jar沒有源代碼附件。 您可以通過單擊下面的附加源附加源: [附加源...] 當我點擊它時,Eclipse會要求我選擇包含'android.jar'的位置文件夾 我試圖做到這一點,但無法導航一直到它所在的文件夾。

我認爲這個問題是在我的代碼的地方。 我一直在尋找小時,甚至複製和粘貼代碼很多次。

回答

5

將實際的Timer(java.util.Timer)與runOnUiThread()一起使用是解決此問題的一種方法,下面是如何實現它的一個示例。

public class myActivity extends Activity { 

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 

    } 
}; 
} 

來源:http://steve.odyfamily.com/?p=12

+2

有很好的理由不利用任何方法除了構造函數和任何變量名稱。 – lhunath

0

嘗試使用Project - > Clean然後右鍵單擊您的項目並找到Fix Project Properties。檢查你的構建路徑。它可能是這些事情中的任何一個。重新啓動eclipse,確保你的Android Manifest的目標是正確的API,8我認爲?

+0

我嘗試了這些,都無濟於事,但在這裏找到了解決辦法:http://steve.odyfamily.com/?p=12 –

相關問題