How to stop the Timer thread? I have a timer thread and I would like to stop it. How do I do it?
I tried to stop by stopping the thread but it was unsuccessful. Any ideas? Thank you in advance for your help
this is my code:
public void startTimer() {
startTime = System.currentTimeMillis();
final Handler handler = new Handler();
task =new Thread() {
@Override
public void run() {
long millis = System.currentTimeMillis()-startTime;
long secs = millis / 1000 % 60; // seconds, 0 - 59
long mins = millis / 1000 / 60 % 60; // total seconds / 60, 0 - 59
long hours = millis / 1000 / 60 / 60; // total seconds / 3600, 0 - limitless
timeString = String.format("%02d:%02d:%02d", hours, mins, secs);
runOnUiThread(new Runnable() {
@Override
public void run() {
mtvtimer.setText(timeString);
}
});
handler.postDelayed(task, 1000);
}
};
task.start();
}
Given that Thread.stop is deprecated, the only option you have is to add some signalling of your own, like a boolean variable that you set when you want it to stop.
e.g.
And from somewhere else, you set
stop = true
to stop it. (this is a rough example code, just to get the idea through)well from the snippet you posted , it is not so clear what you want to achieve. You are passing the task , in the handler to be TimerJob and at the same time , you call task.start() , which means , every time the task is starting , it will attach another task to the handler , as long as with the UiThread. So if i have understood correctly your logic , you could do something like the below example :
Seems like this is a job for a timer: