I want to get some data from the network in a while loop until the user clicks a button on the screen, then stop to receive the data and show another activity. What I do to receive is as follows:
Thread listUpdater;
…
listUpdater = new Thread() {
@Override
public void run() {
TimerTask task = new UpdateListTask();
while (true) {
task.run();
}
}
};
listUpdater.start();
…
public class UpdateListTask extends TimerTask {
public UpdateListTask() {
}
@Override
public void run() {
// get some data from network (asynchronically)
}
}
Once the user has clicked a button, I run the following code:
try {
listUpdater.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
But it doesn’t stop the run loop in the new thread/timer task, all code is still being run – what I don’t want. What can I do to stop the code being run? Is there a way to stop the thread? Or can I do some inter-thread-boolean variable setting to stop the while loop?
I tried everything but didn’t succeed. Can anyone please help?
.join waits until the thread is finished. Your thread will never finish, and so everything breaks.
An easy way to actually stop the thread is this:
…
and
This way you use the boolean variable as a flag with which to control the execution of your listUpdater thread. Remember to set it back to true every time you want to relaunch the thread.