onPause、onStop、onDestroy不停止计时器



在我的活动中的onCreate方法中,我从对象中调用一个方法,并将methods值传递为1,这意味着在对象类中启动计时器。然而,每当应用程序关闭、失去焦点或有人按下设备上的后退按钮退出应用程序时,我都想停止计时器。我尝试在onCreate方法下面使用onPause、onStop和onDestroy执行此操作,并为对象输入方法值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) {

}

}

我不明白为什么你的计时器没有取消。但你的代码中还有另一个错误:你不能通过调用resume和start来暂停和恢复倒计时计时器。

如果你的时间被取消了,你应该省下旧的定时器。如果您的计时器必须恢复,您可以使用旧的计时器值创建一个新的计时器。请参阅:安卓系统:如何暂停和恢复倒计时?

对于你的问题:你能调试并检查是否调用了onPause、onStop和onDestroy吗?是否引发了任何异常?你有任何编译警告吗?

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

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

最新更新