[英]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.