android倒计时器取消vs timeup

时间:2013-12-26 09:59:16

标签: android countdowntimer

我只是想知道何时发生超时,调用onFinish()方法,我们可以在那里执行更多代码。但出于某种原因,如果手动取消定时器或因错误而被onFinish()调用?或者它只是在不调用任何方法的情况下取消定时器。

这是我的两个计数器。

C1的:

    class Counter1 extends CountDownTimer {

    public Counter1(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onFinish() {
        // TODO Auto-generated method stub
        Log.d(TAG, " Timer1 Finished");
                    //Add 2min to second timer


    }

    @Override
    public void onTick(long millisUntilFinished) {
        // TODO Auto-generated method stub
                    /
    }
}

class Counter2 extends CountDownTimer {

    public Counter2(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        // TODO Auto-generated constructor stub
    }
    @Override
    public void onFinish() {
        // TODO Auto-generated method stub
        Log.d(TAG, "Timer2 Finished");          
    }
    @Override
    public void onTick(long millisUntilFinished) {
        // TODO Auto-generated method stub
    }
}

我必须向第二个计时器添加2分钟,因为它的值小于其现有的2分钟,否则它将继续使用其计时器。

1 个答案:

答案 0 :(得分:0)

OnFinish()不会在取消定时器时调用取消你必须再次启动它。当应用程序崩溃时你可以将时间值存储在共享首选项中,你有从保存时间开始的时间。

CountDownTimer countDownTimerFixed = new CountDownTimer(Time, Tick) {

    @Override
    public void onTick(long millisUntilFinished) {

        RTSharedPrefUtils.saveStringPrefernce(RTSharedPrefUtils.KEY_DOWNLOAD_TIMER, millisUntilFinished+ "");

    }

    @Override
    public void onFinish() {
        // TODO Auto-generated method stub

        RTSharedPrefUtils.saveStringPrefernce(RTSharedPrefUtils.KEY_DOWNLOAD_TIMER, 0 + "");
        this.start();

    }
};  

如果计时器被取消,

Timer=Long.parseLong(RTSharedPrefUtils.fetchStringPrefernce(RTSharedPrefUtils.KEY_DOWNLOAD_TIMER,RTSharedPrefUtils.DEFAULT_DOWNLOAD_TIMER));

            countDownTimer = new CountDownTimer(Timer, Tick) {

                @Override
                public void onTick(long millisUntilFinished) {



                    RTSharedPrefUtils.saveStringPrefernce(
                            RTSharedPrefUtils.KEY_DOWNLOAD_TIMER,millisUntilFinished + "");
                    Log.d(TAG," Normalcount:\t"+ (Long.parseLong(RTSharedPrefUtils.fetchStringPrefernce(RTSharedPrefUtils.KEY_DOWNLOAD_TIMER,RTSharedPrefUtils.DEFAULT_DOWNLOAD_TIMER)))/ 1000);
                }

                @Override
                public void onFinish() {
                    // TODO Auto-generated method stub

                    }
                    RTSharedPrefUtils.saveStringPrefernce(
                            RTSharedPrefUtils.KEY_DOWNLOAD_TIMER, 0 + "");

                    countDownTimerFixed.start();

                }

};

countDownTimer.start();