timer.scheduleAtFixedRate does not stop when i call cancel
Here is your code put into my file, with the values delay and period tweaked so I don't have to wait so long. I run the app. I see the messages in LogCat. I press the home button on my Galaxy S3. Then the messages stop in LogCat.
public class MainActivity extends Activity {
Timer myTimer;
TimerTask doThis;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTimer = new Timer();
int delay = 0; // delay for 30 sec.
int period = 1000; // repeat every 60 sec.
doThis = new TimerTask() {
public void run() {
Log.v("TImer","repeated");
}
};
myTimer.scheduleAtFixedRate(doThis, delay, period);
}
@Override
protected void onPause() {
myTimer.cancel();
super.onPause();
}
}
Daler
Im an Android developer that wants finally to finish a one little project and put it in play market, so far it seems difficult for me. Well, i will not give up. OK)
Updated on July 26, 2022Comments
-
Daler almost 2 years
At onCreate, I run a task that repeats every minute. Here how I do it:
myTimer = new Timer(); int delay = 30000; // delay for 30 sec. int period = 600000; // repeat every 60 sec. doThis = new TimerTask() { public void run() { Log.v("TImer","repeated"); wv.reload(); } }; myTimer.scheduleAtFixedRate(doThis, delay, period);
All that code is in onCreate. So, when the app goes off from the screen, I can see in logcat that timer steel runs, and will not stop unless the app will be destroyed. So, in
onPause
of activity I callmyTimer.cancel();
but it didnt help. I still can see updates in logcat, even when the app is not on the screen. So, how to stoptimerTask
? -
Anthony Tietjen over 11 yearsYour code works for me, except I took of wv.reload(); -- Not sure what you are doing in that method. Is it something that would cause the app to start again?
-
Anthony Tietjen over 11 yearsAlso, can you put a Log.v on your onPause method to make sure it is actually getting fired?
-
Daler over 11 yearswv.reload, i just reload a webview. strange that it works for you
-
Anthony Tietjen over 11 yearsStrange. Does Log.v show anything in your onPause method? If not, I think it might be spelled wrong, or maybe your P is not upper case or something else out of place -- so it is not actually being called.