Template for reusing Android AsnycTask in multiple actions?

I have several subclasses of Activity in my project, each of which calls a SOAP-based web service, processes and displays the results. SOAP serialization, call processing, and parsing of the result into various POJOs are encapsulated in the MyWebService class. This class makes an actual web service call through AsyncTask.

In order to pass the results to a subclass of the calling activity, I decided that all these actions should implement the WebServiceResultProcessor interface defining one function (processWebServiceResults) acting as a callback for AsyncTask called from onPostExecute.

I also want to display the ProgressDialog during a web service call. And here is my question. In order to display the ProgressDialog (either from MyWebService or AsyncTask), I need to pass a link to the caller's activity context. And in order to execute the callback function from AsyncTask, I also need to pass the same object reference, but this time as a WebServiceResultProcessor. It seems to me like a code smell, passing the same object twice, but I see no way around it. Instead of interacting, I could create a new base class by extending the Activity class and applying inheritance from the extension class, but this would mean that I excluded ListActivity and the like from this MyWebService class.

Is there a better way to do this?

+5
source share
3 answers

Despite Arhimed's warning, I ended up using AsyncTask as it is still suitable for my purposes. I just make sure that all the actions that invoke the web services onDestroy()send the cancel()called AsyncTask after them . The AsyncTask implementation itself handles the cancellation request gracefully, checking isCancelled () wherever it is needed.

Regarding the initial question, I had to leave - the solution is really simple. I pass the instance of the Activity subclass as an object to AsyncTask and pass it either to the context or to the WebServiceResultProcessor, if necessary. Snippets showing how this works:

if (callerActivity instanceof Context) {
    ProgressDialog dialog = new ProgressDialog((Context)callerActivity);
}

...

if (callerActivity instanceof WebServiceResultProcessor) {
    ((WebServiceResultProcessor)callerActivity).processWebServiceResults(soapObject);
}
0
source

+1, a good question!

. , AsyncTask . , AsyncTask Activity ( ProgressDialog , onPostExecute()).

: Android Activity, AsyncTask doInBackground(). , , - , . : , , , . , .

, Google , . , : " ". . , Google , . " Google I/O 2010 - REST Android" . , , Android.

+4

You might look at this blog article ( part 1 and part 2 ) that implements a web service with AsyncTaskLoader and the same web service with a Service component. In addition, it shows the differences between the two approaches, as well as interesting comments on this article.

+3
source

All Articles