我正在使用 Android 版 Eclipse。我正在尝试制作一个具有短暂延迟的简单重复计时器。 它将在单击 TextView timerTV 后启动。这段代码在onCreate方法中:
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”的位置文件夹 我尝试这样做,但无论如何都无法导航到它所在的文件夹。
我认为问题出在我的代码中的某个地方。 我已经搜索了几个小时,甚至多次复制和粘贴代码。
最佳答案
结合使用实际的计时器 (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
}
};
}
关于android - 如何设置真正有效的 Timer.scheduleAtFixedRate() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11217930/