在我的活动中的onCreate方法中,我从一个对象中调用一个方法,并将方法值传递为1,这意味着在对象类中启动一个计时器。但是,我想停止计时器,每当应用程序关闭,失去焦点或有人按下他们的设备上的后退按钮,并退出应用程序。我尝试使用onPause,onStop,onDestroy在我的onCreate方法下面执行此操作,并将对象的方法值输入为2,这意味着取消定时器。然而,我的问题是,无论何时有人按下设备上的后退按钮,然后返回到应用程序,相同的定时器运行两次,因为该应用程序没有取消onStop,onPause或onDestroy中的定时器。为什么onStop,onPause和onDestroy不能停止计时器,并且如何让它停止计时器,以便在应用程序重新打开时两个都没有运行?下面onPause,onStop,onDestroy不停止定时器
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();
}
}
Timer类
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) {
}
}
活动下
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);
}
船级
我编辑了这个问题,并把我的计时器课。 – Xetron 2014-10-20 19:22:27