Reputation: 4837
I have an AsyncTask with a field named "sardine", in doInBackground() I call sardine.put(...) which makes network operations and run synchron. Now, while this is running, I need to be able to call sardine.abort() in a public method of the AsyncTask. I read that I should do a synchronized block on (this) but I am not sure of the consequences of this, now I am doing following:
public class AsyncWebDavUploadFile extends AsyncTask<Void, Long, Integer> {
private SardinePatched sardine;
@Override
protected Integer doInBackground(final Void... params) {
...
sardine = new Sardine...
sardine.put(urlString, fileInputStream, mimeType, file.length(), true);
...
return result;
}
public void stopUplaod() {
new Thread(new Runnable() {
@Override
public void run() {
if (sardine != null) {
synchronized (sardine) {
sardine.abort();
}
}
}
}).start();
}
...
}
"sardine.put" does an "AbstractHttpClient.execute" and sardine.abort does an HttpRequestBase.abort, but I don't think this matter.
Upvotes: 0
Views: 909
Reputation: 6410
Use an AsyncTaskLoader and the LoaderManager. Then you can call Loader.cancelLoad.
http://developer.android.com/reference/android/content/AsyncTaskLoader.html
If you don't want to do than then using cancel(true) on the AsyncTask will interrupt it. You don't need any synchronized blocks or any new threads. Just handle the interrupted exception in the background method.
Upvotes: 2