当前位置: 首页 > 知识库问答 >
问题:

如何清除CountDownTimer从onTick方法?

夔光霁
2023-03-14

我已经在android应用程序中实现了计时器功能,我可以通过调用timerObject从其他本地方法完成计时器。取消()。它工作得很好。

但是,当我试图在onTick()方法中为特定条件调用相同的函数时,我无法取消计时器,它将一直持续到计时器时间结束。

如何取消计时器?

共有3个答案

严正初
2023-03-14

如果使用RXJava2。这段代码可以帮助你。

    public abstract class CountDownTimer { 

    private TimeUnit timeUnit;
    private Long startValue;
    private Disposable disposable;

    public CountDownTimer(Long startValue,TimeUnit timeUnit) {
        this.timeUnit = timeUnit;
        this.startValue = startValue;
    } 

    public abstract void onTick(long tickValue);

    public abstract void onFinish(); 

    public void start(){ 
        io.reactivex.Observable.zip( 
                io.reactivex.Observable.range(0, startValue.intValue()), io.reactivex.Observable.interval(1, timeUnit), (integer, aLong) -> {
                    Long l = startValue-integer;
                    return l; 
                } 
        ).subscribeOn(Schedulers.io()) 
                .observeOn(AndroidSchedulers.mainThread()) 
                .subscribe(new Observer<Long>() { 
                    @Override 
                    public void onSubscribe(Disposable d) { 
                        disposable = d; 
                    } 

                    @Override 
                    public void onNext(Long aLong) { 
                        onTick(aLong); 
                    } 

                    @Override 
                    public void onError(Throwable e) { 
                        e.printStackTrace(); 
                    } 

                    @Override 
                    public void onComplete() { 
                        onFinish(); 
                    } 
                }); 
    } 

    public void cancel(){ 
        if(disposable!=null) disposable.dispose();
    } 
}

使用:

public class MainActivity extends AppCompatActivity { 

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start_activity);

        new CountDownTimer(10L, TimeUnit.SECONDS) {

            @Override 
            public void onTick(long tickValue) {
                Log.d("CountDown", "Remaining: " + tickValue);

                // cancel();
            } 

            @Override 
            public void onFinish() { 
                Log.d("CountDown", "The End!! ");
            } 
        }.start();
    } 
} 

代码的所有者https://gist.github.com/chemickypes/fa3b7fc5b5a00a3ce37fee5815018702

鲁品
2023-03-14

查看CountDownTimer的源代码,很容易看出它不起作用的原因cancel()仅从队列中删除用于勾选计时器的消息。但是在每次勾选时被调用的消息处理程序在调用onTick()后为下一个勾选发布消息。因此,您必须在onTick()之外通过处理程序调用cancel(),例如,或者切换到使用Timer类。

柴文林
2023-03-14

好吧,你不能那样做

但是Android CountDownTimer类还有一个替代方案,但是您可以在onTick中取消它。

干得好

/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package alt.android.os;

import android.util.Log;
import android.os.Handler;
import android.os.SystemClock;
import android.os.Message;

/**
 * Schedule a countdown until a time in the future, with
 * regular notifications on intervals along the way.
 *
 * Example of showing a 30 second countdown in a text field:
 *
 * <pre class="prettyprint">
 * new CountdownTimer(30000, 1000) {
 *
 * public void onTick(long millisUntilFinished) {
 * mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
 * }
 *
 * public void onFinish() {
 * mTextField.setText("done!");
 * }
 * }.start();
 * </pre>
 *
 * The calls to {@link #onTick(long)} are synchronized to this object so that
 * one call to {@link #onTick(long)} won't ever occur before the previous
 * callback is complete. This is only relevant when the implementation of
 * {@link #onTick(long)} takes an amount of time to execute that is significant
 * compared to the countdown interval.
 */
public abstract class CountDownTimer {

    /**
     * Millis since epoch when alarm should stop.
     */
    private final long mMillisInFuture;

    /**
     * The interval in millis that the user receives callbacks
     */
    private final long mCountdownInterval;

    private long mStopTimeInFuture;

    private boolean mCancelled = false;

    /**
     * @param millisInFuture The number of millis in the future from the call
     * to {@link #start()} until the countdown is done and {@link #onFinish()}
     * is called.
     * @param countDownInterval The interval along the way to receive
     * {@link #onTick(long)} callbacks.
     */
    public CountDownTimer(long millisInFuture, long countDownInterval) {
        mMillisInFuture = millisInFuture;
        mCountdownInterval = countDownInterval;
    }

    /**
     * Cancel the countdown.
     *
     * Do not call it from inside CountDownTimer threads
     */
    public final void cancel() {
        mHandler.removeMessages(MSG);
        mCancelled = true;
    }

    /**
     * Start the countdown.
     */
    public synchronized final CountDownTimer start() {
        if (mMillisInFuture <= 0) {
            onFinish();
            return this;
        }
        mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
        mHandler.sendMessage(mHandler.obtainMessage(MSG));
        mCancelled = false;
        return this;
    }


    /**
     * Callback fired on regular interval.
     * @param millisUntilFinished The amount of time until finished.
     */
    public abstract void onTick(long millisUntilFinished);

    /**
     * Callback fired when the time is up.
     */
    public abstract void onFinish();


    private static final int MSG = 1;


    // handles counting down
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            synchronized(CountDownTimer.this) {
                final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();

                if (millisLeft <= 0) {
                    onFinish();
                } else if (millisLeft < mCountdownInterval) {
                    // no tick, just delay until done
                    sendMessageDelayed(obtainMessage(MSG), millisLeft);
                } else {
                    long lastTickStart = SystemClock.elapsedRealtime();
                    onTick(millisLeft);

                    // take into account user's onTick taking time to execute
                    long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();

                    // special case: user's onTick took more than interval to
                    // complete, skip to next interval
                    while (delay < 0) delay += mCountdownInterval;

                    if (!mCancelled) {
                        sendMessageDelayed(obtainMessage(MSG), delay);
                    }
                }
            }
        }
    };
}
 类似资料:
  • 我有Android的代码 其中“timeUntilStageTwo”是直到第二天的某个小时的时间,所以我想在每秒钟(在onTick方法中)刷新文本视图并更改其文本。问题是这个onTick方法只被调用几次,然后就完全停止被调用了,这是为什么呢?关键是我想在活动中做一个计时器,直到给定的小时

  • 我正在使用一个简单的并每隔毫秒调用: 问题是虽然计时器在正确的时间结束,但是方法并没有每毫秒被调用一次。每次都少了几毫秒。 我使用日志检查它,发现的值在最后是597,而它应该是999,因为每次调用时它都会得到1。有精度误差吗?

  • 当Kubernetes pod进入状态时,您将修复底层问题。你怎么强迫它重新安排?

  • 我正在创建一个简单的程序,在那里我画一个黑色的椭圆形,在那里我用鼠标点击。然而,我希望一个新的椭圆形出现,旧的消失。我该怎么做?我把removeAll()方法插入到我的mousePressed方法中,但它对我不起作用。removeAll()方法是否适用于此?还是我应该用别的?很抱歉,如果答案很明显,但我仍然是新手,并试图学习。任何建议都将不胜感激。谢谢

  • 问题内容: 我在Swift 2中使用SFSafariViewController在具有ios 9.1(13B143)的iPad Air 2上显示网页。每个网页都需要用户提供凭据。但是,当用户按下注销按钮时,我需要清除这些凭据。我尝试使用以下方法: 但这不起作用。实际上,“ DELETING CREDENTIAL”和“ DELETING COOKIE”从未打印过。此外,我可以从iPad上完全删除该应

  • 问题内容: 在导入flask时,我们导入模块等。 是一种字典,可以使用会话进行访问。 现在,我尝试清除尝试构建网站时使用的所有垃圾变量。 关于stackoverflow的答案之一使用了类似清除会话内容的命令。但是,这样的命令会产生错误,表明不存在这样的命令。 谁能为我指出每次关闭服务器或关闭网站时如何清除和如何清除会话? 问题答案: 我将这样的会话与flask一起使用,它确实起作用。我虽然不使用,