In my android app, I have the following relevant piece of code:
/*Code outside*/
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Timer t = new Timer();
t.scheduleAtFixedRate(
new TimerTask(){
public void run(){
stuffToBeDone();
}
},someVariableDelay,someVariablePeriod);
}
}
Everything was going fine until I noticed that stuffToBeDone() was running once for every time I pressed the button. As far as I understand, every time onClick() is called and the old Timer should not exist anymore, but somehow the TimerTask survives.
In the second button click, I no longer have a reference to the first Timer to cancel() it (because it should not exist anymore). And if I declare the Timer as a final variable in the Code outside so that I can do it, after canceling I cannot reuse it anymore. So how can I terminate that TimerTask but then still be able to use a Timer?
Android Timer is thread based from the Android Developers website:
http://developer.android.com/reference/java/util/Timer.html
When a timer is no longer needed, users should call cancel(), which releases the timer's thread and other resources. Timers not explicitly cancelled may hold resources indefinitely.
I would recommend instantiating the timer inside the onclicklistener only i.e. something similar to this:
/*Code outside*/
Timer t = null;
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(t == null)
t = new Timer();
else
t.cancel();
t.scheduleAtFixedRate(
new TimerTask(){
public void run(){
stuffToBeDone();
}
},someVariableDelay,someVariablePeriod);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With