【发布时间】:2014-10-20 18:35:04
【问题描述】:
在我的活动中的 onCreate 方法中,我从对象调用方法并将方法值传递为 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) {
}
}
【问题讨论】: