Reputation: 1719
I'm trying to execute some function repeatedly for every 5 sec & it's working fine.
I wanted this timer to stop when the app is closed or back button is pressed.
int delay = 0;
int period = 5000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("done");
}
}, delay, period);
}
Upvotes: 0
Views: 198
Reputation: 13
In Android you can override below methods to identify the back press and activity close, then you can have the code to cancel the timer. 1. onDestroy() 2. onBackPressed()
In method implementation you can use below statements to stop. timer.cancel(); timer.purge();
ex:
@Override
public void onBackPressed() {
timer.cancel();
timer.purge();
super.onBackPressed();
}
I guess this would help..
Upvotes: 1
Reputation: 7663
Don't use a Timer
just use a Handler
private boolean keepLooping = true;
private static final int DELAY = 1000 * 5;
final Handler printHandler = new Handler();
Runnable printStuff = new Runnable(){
@Override
public void run(){
System.out.println("done");
if(keepLooping)
printHandler.postDelayed(this, DELAY);
}
}
//wherever you want to start your printing
printHandler.postDelayed(printStuff, DELAY);
keepLooping = true;
//when back is pressed or app is stopped
keepLooping = false;
printHandler.removeCallbacks(printStuff);
postDelayed will run the runnable on the delay you want. If you want it to loop forever just start the handler again from within the runnable. When you want it to stop just removeCallbacks which will prevent the looping.
Upvotes: 3