倒数计时器取消不起作用

时间:2017-06-16 03:57:08

标签: android performance android-layout timer countdowntimer

这已被多次询问,但我仍然不确定如何解决它,

我创建了一个从CountDownTimer扩展的类。

  

公共类CounterClass扩展了CountDownTimer

这个类是单例,所以3个活动正在使用它,并且所有这些类的计时器值都是相同的;这很好。

但是当用户按下后退按钮时,从activity 1开始,我想要重置计时器值。

这是我正在做的取消计时器。

   CounterClass.getInstance().cancel();

   CounterClass.elapsedTime = -1; 

类文件

public  class CounterClass extends CountDownTimer {

    static CounterClass  instance;

    public static CounterClass getInstance(){
        if(instance == null) {
            instance = new CounterClass(millisInFutureConitunationValue, 1);
        }

        return instance;
    }


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

    private CounterClass(long millisInFuture, long countDownInterval) {
        super((elapsedTime < 0)?millisInFuture:elapsedTime, countDownInterval);
    }


    public void setContext(Context context){
        this.context= context;
    }

    @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);
    }

0 个答案:

没有答案