Reputation: 1285
i have a problem with a method that i want to be called every x seconds. In the constructor of my class I have something like that :
public class MyClass extends RelativeLayout{
public MyClass(Context context) {
// bla bla….
mTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
callMyMethodPeriodically();
}
}, 0, 20000); // every 20 seconds..
}
}
When I press the back button, the callMyMethodPeriodically method still is being called.. Even if i exit the application! Do you have any ideas?? How can i stop this periodically calling? Thank you
Upvotes: 1
Views: 53
Reputation: 1551
Try to override the onPause method on your Activity, the onPause will be called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.
@Override
protected void onPause() {
super.onPause();
mTimer.cancel();
mTimer.purge();
mTimer = null;
}
Upvotes: 2
Reputation: 3772
You can try timer.canel() method or you can do it by this way
private Runnable runnable = new Runnable() {
public void run()
{
//
// Do the stuff
//
handler.postDelayed(this, 1000);
}
};
and to stop:
handler.removeCallbacks(runnable);
or this way
you could look into using a ScheduledThreadPoolExecutor instead of a Timer.
Usage is pretty straight forward. You create an instance of an executor:
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor( 1 );
And then when you want to add a task you call:
executor.scheduleAtFixedRate( myRunnable, delay, interval, unit );
Where myRunnable is your task (which implements the Runnable-interface), delay is how long before the task should be executed the first time, interval is time between the execution of the task after first execution. delay and interval are meassured based on the unit parameter, which can be TimeUnit.* (where * is SECONDS, MINUTES, MILLISECONDS etc.).
Then to stop the execution you call:
executor.shutdownNow();
Upvotes: 1