How to stop thread safely in android? [duplicate]
h开发者_开发问答ow can I stop threads safely?
downloadThread = new Thread(new Runnable() {
@Override
public void run() {
});
downloadThread.start();
}
Instead of using normal thread to do background jobs if u will use Android sdk's AsyncTask
, there you can find a cancel()
.
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.
精彩评论