how can I stop threads safely?
downloadThread = new Thread(new Runnable() {
@Override
public void run() {
});
downloadThread.start();
}
how can I stop threads safely?
downloadThread = new Thread(new Runnable() {
@Override
public void run() {
});
downloadThread.start();
}
Interrupt the thread. In the run()
method of the thread, check the value of isInterrupted()
at the end of different logical blocks.
For instance, say your run()
method can be broken up into three logical steps
- creating a network connection, downloading an image and saving the image to a file. At the end of each of these steps, check for isCancelled()
and stop the operation discarding all state at that point.
class NetworkFetcherTask extends AsyncTask<String, Void, Void>{
public void doInBackground(String... params){
String url = params[0];
//Open connection if not cancelled
if(isCancelled()){
conn.close();
return;
}
NetworkConnection conn = new NetworkConnection();
//Download the image if not cancelled
if(isCancelled()){
conn.close();
result.discard();
return;
}
NetworkResult result = conn.fetchUrl(url);
conn.close();
//Save the image to a file if not cancelled
if(isCancelled()){
result.discard();
return;
}
File file = new File();
file.dump(result);
}
}
The easiest one seem to be setting isRunning to false.