CountDownTimer onTick()无法更新类的成员

时间:2017-06-19 14:56:48

标签: java android countdowntimer

我在onTick()方法中更新CountDownTimer中的字段。但是,该字段始终为0.您是否知道导致问题的原因是什么?

public class Counter {

    private static final long SECOND_MS = 1000;
    private static final long MINUTE_MS = 60 * SECOND_MS;
    private static final long TOTAL_TIME_MS = 5 * MINUTE_MS;

    public long mSecondsSinceLastPick;

    public long getSecondsSinceLastSchedulerStarted() {
        Timber.d( String.format("get mSecondsSinceLastPick = %s", mSecondsSinceLastPick) );
        return mSecondsSinceLastPick;
    }


    private CountDownTimer mCountDownTimer = new CountDownTimer(TOTAL_TIME_MS, SECOND_MS) {

        public void onTick(long millisUntilFinished) {
            Timber.d( String.format("onTick mSecondsSinceLastPick = %s", mSecondsSinceLastPick) );
            mSecondsSinceLastPick = (TOTAL_TIME_MS - millisUntilFinished) / SECOND_MS;
        }

        public void onFinish() {
        }
    };

public void startCounting() {
    mCountDownTimer.start();
}
}

[EDITED] 日志输出类似于

06-19 15:42:57.293 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 4
06-19 15:42:58.293 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 5
06-19 15:42:59.299 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 6
06-19 15:43:00.320 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 7
06-19 15:43:01.321 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 8
06-19 15:43:01.507 9994-9994/com.nav.survey D/GroundTruthReminderManager:22: get mSecondsSinceLastPick = 0
06-19 15:43:02.322 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 9
06-19 15:43:03.324 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 10
06-19 15:43:04.325 9994-9994/com.nav.survey D/GroundTruthReminderManager:38: onTick mSecondsSinceLastPick = 11

2 个答案:

答案 0 :(得分:1)

问题是你没有启动计时器

<h1>Default font</h1>
<h2>Default font</h2>
<p>Changed font</p>
<h3>Default font</h3>

 mCountDownTimer.start();

答案 1 :(得分:0)

问题在于创建我的计数器。我使用Dagger @Singleton注释来提供Counter,但是,无论如何都创建了2个Counter实例并且它引起了问题。