My Activity has an AsyncTask
whose doInBackground
method you can see below. I have to make multiple search request to multiple servers and in order to speed up the execution I've used Java's ExecutorService
to make concurrent requests.
This works fine but I'd like my AsyncTask
to stop whatever it is doing and quit, if I call the AsyncTask.cancel();
method with true
as the mayInterruptIfRunning
parameter. This is useful in situations where I need to stop the task when my Activity
exits e.g. the "Back" button is pressed.
I've read that calling the cancel()
method of the AsyncTask
will prevent the onPostExecute
method from being invoked, but the doInBackground
will run until it is finished.
Is there a way, I could interrupt my Callables
and force them to stop whatever it is they are doing and stop the AsyncTask
.
I have posted an abridged version of my code here for brevity, but I have a bunch of a Callables
, not just one.
Thanks.
protected ArrayList<Result> doInBackground(final String... strQuery) {
ArrayList<Result> objResults = new ArrayList<Result>();
ExecutorService esrExecutor = Executors.newFixedThreadPool(2);
Set<Callable<ArrayList<Result>>> setCallables = new HashSet<Callable<ArrayList<Result>>>();
setCallables.add(new Callable<ArrayList<Result>>() {
public ArrayList<Result> call() throws Exception {
try {
MySearcher objSearcher = new MySearcher(Finder.this.objContext);
ArrayList<Result> objResults = new ArrayList<Result>();
objResults = objSearcher.doSearch(strQuery[0]);
return objResults;
} catch (Indexer.LoginException e) {
return null;
}
return null;
}
});
List<Future<ArrayList<Result>>> lstFutures;
try {
lstFutures = esrExecutor.invokeAll(setCallables);
for(Future<ArrayList<Result>> futFuture : lstFutures){
if (futFuture.get().isEmpty() == false)
objResults.addAll(futFuture.get());
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
esrExecutor.shutdown();
return objResults;
}