简体   繁体   English

即使取消,倒数计时器也不会停止

[英]Countdown timer does not stop even after cancel

This is how i am using CountdownTimer in my application 这就是我在应用程序中使用CountdownTimer的方式

I am calling it from Fragment 我从Fragment叫它

CounterClass counterClass=CounterClass.getInstance(180000,1000);
counterClass.setTextView(tvTimer);
counterClass.setContext(getActivity().getApplicationContext());
counterClass.start();

and when user presses back button from activity, i use this code 当用户从活动中按下返回按钮时,我使用此代码

CounterClass.getInstance().cancel();
CounterClass.getInstance().onFinish();

but this is not helping, I have added a Log message in onTick , i can see the tick continuously working even after cancel is called. 但这onTick ,我在onTick添加了一条Log消息,即使调用了cancel之后,我仍然可以看到滴答声继续起作用。

This is my implementation of CountDownTimer 这是我的CountDownTimer实现

public  class CounterClass extends CountDownTimer {


     public static CounterClass getInstance(long millisInFuture, long countDownInterval){
        instance = new CounterClass(millisInFuture, countDownInterval);
        return instance;
    }



@Override
    public void onTick(long millisUntilFinished) {
        long millis= millisUntilFinished;
        elapsedTime = millisUntilFinished;

        String hms= String.format("%02d:%02d",
        TimeUnit.MILLISECONDS.toMinutes( millisUntilFinished),
        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
        tvTimer.setText(hms);

}

}

Kindly guide me how stop and reset timer. 请指导我如何停止和重置计时器。 I have also tried boolean approach, where i set and checked boolean in onTick , but that also didnt work. 我还尝试了boolean方法,在onTick设置并检查了布尔值,但这也没有用。

You are creating a new instance of your counter class upon each call to getInstance() . 您将在每次调用getInstance()时创建计数器类的新实例。 For this singleton pattern, you will want to return the same instance each time. 对于此单例模式,您将希望每次都返回相同的实例。 What is happening now is that you are cancelling a new instance while the old instance continues to run. 现在发生的事情是您在取消旧实例继续运行的同时取消新实例。 You will need to make a mod to your code something like this: 您将需要对代码进行修改,如下所示:

public  class CounterClass extends CountDownTimer {

     private static CounterClass sInstance;

     public static CounterClass getInstance(long millisInFuture, long countDownInterval){
        if (sInstance == null) {
            sInstance = new CounterClass(millisInFuture, countDownInterval);
        }
        return sInstance;
    }
    ...

You also probably don't need to call onFinish() yourself and should let the framework do that for you. 您可能还不需要自己调用onFinish()而应让框架为您完成此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM