onPause,onStop,onDestroy不停止计时器

时间:2014-10-20 18:35:04

标签: java android timer

在我的活动中的onCreate方法中,我从一个对象调用一个方法,并将方法值传递为1,这意味着在对象类中启动一个计时器。但是我想在应用程序关闭时停止计时器,失去焦点或有人按下设备上的后退按钮并退出应用程序。我尝试使用onPause,onStop,onDestroy在我的onCreate方法下执行此操作,并将对象的方法值输入为2,这意味着取消计时器。然而我的问题是,每当有人按下他们设备上的后退按钮然后返回到应用程序时,同一个计时器正在运行两次,因为应用程序没有取消onStop,onPause或onDestroy中的计时器。为什么没有onStop,onPause和onDestroy停止计时器,如何让它停止计时器,以便在重新打开应用程序时两个不运行?

以下活动

Ship mShip = new Ship(0,0,0);

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

        mShip.timerStart(1);

}


@Override
public void onPause()
{
    super.onPause();
    mShip.timerStart(2);
}
@Override
public void onStop()
{
    super.onStop();
    mShip.timerStart(2);
}
@Override
public void onDestroy()
{
    super.onDestroy();
    mShip.timerStart(2);
}

下面的船级

    public static int counter = 0;
    public static int counterPerSec = 5;

TimerClass startTimer = (TimerClass) new TimerClass(2000,1000)
    {
        @Override
        public void onFinish() {
           counter += counterPerSec;
            this.start();
        }
    };


    public void timerStart(int x) {

        if(x == 1)
        {
           startTimer.start();
        }

        if(x == 2)
        {
           startTimer.cancel();
        }

    }

计时器类

public class TimerClass extends CountDownTimer {
public TimerClass(long millisInFuture, long countDownInterval) {
    super(millisInFuture, countDownInterval);
}


@Override  // when timer is finished
public void onFinish() {
    this.start();

}
@Override  // on every tick of the timer
public void onTick(long millisUntilFinished) {



}

}

2 个答案:

答案 0 :(得分:0)

好吧,我想我可以正确地假设onPause,onStop和onDestroy正在执行,所以我冒昧地猜测你的TimerClass类中有一个错误。

答案 1 :(得分:0)

我看不出,为什么你的计时器没有被取消。但是您的代码中还有另一个错误:您无法通过调用resume并启动来暂停和恢复倒数计时器。

如果您的时间被取消,您应该保存旧计时器vaules。如果必须恢复计时器,则可以使用旧计时器值创建新计时器。请参阅:Android: How to pause and resume a Count Down Timer?

您的问题:您可以调试并检查onPause,onStop,onDestroy是否被调用?有没有抛出异常?你有任何编译警告吗?

最后一个重要问题:你怎么知道两个计时器正在运行?

相关问题