我有一个CountDownTimer,它需要一直运行。有2项活动(A和B)。 Activity A具有CountDownTimer,它更新其中的TextView。当我切换到B时,CountDownTimer仍然运行(这是所需的行为),但当我切换回A时,似乎有一个旧的和新的A.计时器不会更新“新”内的TextView A.首次访问A时,它仅启动一次。有关如何解决这个问题的任何想法?也许把计时器放在其他地方? 修改:部分代码:
private void prepareTimer() {
// TODO: DOES NOT WORK YET! (switching activities -> runs in old activity)
textTime = (TextView) findViewById(R.id.text_time); // is a field
if (!timerRunning) {
timerRunning = true;
int duration = 60000;
timer = new CountDownTimer(duration, 1000) {
public void onTick(long millisUntilFinished) {
long minsLeft = (long) Math.floor((double) millisUntilFinished / (double) Constants.ONE_MINUTE) + 1;
textTime.setText(minsLeft + " Min.");
}
public void onFinish() {
textTime.setText("done!");
}
};
timer.start();
}
}
答案 0 :(得分:0)
CDT
正在自己独立的线程中运行。您尝试访问的TextView
引用,CDT
不再可用(因为您在B中时不再显示您的活动A)尝试创建TextView
的新引用返回A时,CDT
线程仍在运行,无论您是从A移动到B还是反之。我希望这将有所帮助。确保在UI线程中进行更改。 ;)
编辑:
private void prepareTimer() {
// TODO: DOES NOT WORK YET! (switching activities -> runs in old activity)
textTime = (TextView) findViewById(R.id.text_time); // is a field
if (!timerRunning) {
timerRunning = true;
int duration = 60000;
timer = new CountDownTimer(duration, 1000) {
public void onTick(long millisUntilFinished) {
long minsLeft = (long) Math.floor((double) millisUntilFinished / (double) Constants.ONE_MINUTE) + 1;
textTime.setText(minsLeft + " Min.");
}
public void onFinish() {
textTime.setText("done!");
}
};
timer.start();
}
else
{
textTime = (TextView) findViewById(R.id.text_time);
}
}