Reputation: 29
I'm making an Android app that turns on/off the flash light after a specified interval, by the user. It works well except when the Timer object is re-created after calling the .cancel() method for the second time, it crashes the app every time. Here's the initialization part:
Timer timer; //variable of Timer class
TimerTask timerTask; //variable of TimerTask class
And here's the method that is called when the button responsible to turn blinking on/off is pressed:
blink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
delay = Integer.valueOf(startDelay.getText().toString());
gap = Integer.valueOf(blinkDelay.getText().toString());
if(!isBlinking) { //isBlinking is a boolean to know whether to stop or re-start timer
timer = new Timer(); //I'm creating an object of Timer class every time.
isBlinking = true;
timer.schedule(timerTask, delay, gap);
}
else{
isBlinking = false;
stoptimertask(); //this will cancel the 'timer' and make it null.
}
}
});
The 'stoptimertask()' method from above code has:
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
I'm setting the 'timertask' variable of TimerTask class from the method shown below. It is called in the onCreate() method of the main activity:
public void initializeTimerTask() {
timerTask = new TimerTask() { //This is passed as the first argument to the timer.schedule() method
public void run() {//Basically turns on/off flash. Works well.
if(!state) {
turnOnFlash();
state = true;
}
else {
turnOffFlash();
state = false;
}
}
};
My question is that why does the app crash when I press the blink button the third time?
Upvotes: 2
Views: 1246
Reputation: 29168
Don't forget to purge
after cancel
.
Your code must be for stoptimertask()
method.
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer.purge();
timer = null;
}
}
Related Link:
UPDATE:
Since Timer creates a new thread, it may be considered heavy,
if all you need is to get is a call back while the activity is running a Handler can be used in conjunction with this link How to set a timer in android
Upvotes: 1
Reputation: 419
You will have to purge as well.
timer.cancel();
timer.purge();
Upvotes: 1