我正在尝试构建一个计时器,该计时器在几秒钟内倒计时并每次更新一次TextView,以便显示剩余时间。从我可以告诉定时器代码工作正常(事件之间1秒,从小时和分钟转换为秒精)因为我已经在Android之外测试它并在android中使用Log.d()。更新textview是什么让我有问题。当我最初尝试更新textview时,我得到空指针,因为只有UI线程可以访问UI(我对错误消息的解释),我添加了runOnUiThread(),允许访问和更新它,但它现在没有正确更新。我认为这就是问题所在,但我并不完全确定,也不知道如何解决问题或提出更好的方法来解决问题。我会欣赏另一双眼睛。谢谢
final static int delay = 1000;
final static int period = 1000;
public void start(int hin, int min) {
run = true;
int hrinsec = (hin * (60 * 60));
int mininsec = (min * 60);
secs = hrinsec + mininsec;
run = false;
interval = secs;
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
// Convert seconds back to hrs and mins
hrsFromSecs(secs);
minsFromSecs(secs);
secsFromSecs(secs);
dint total = hours + minutes + seconds;
output = hours + " Hours " + minutes + " Minutes " + seconds
+ " Seconds";
// Countdown and update the textview
runOnUiThread(new Runnable() {
@Override
public void run() {
timer.setText(output);
}});
secs = secs - 1;
checkIfDone(total);
}
}, delay, period);
}