我在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();
}
}


[编辑]
日志输出看起来像

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

最佳答案

问题是您不启动计时器

 mCountDownTimer.start();


要么

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() {
    }
}.start();

关于java - CountDownTimer onTick()无法更新类的成员,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44633848/

10-11 00:28