在我的活動中的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