2012-06-27 29 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 –

相关问题