Updating a ProgressDialog using an AsyncTask
I need a AsyncTask to run my ProgressDialog while I'm fetching data from the network. I understand the AsyncTask. But I have the network calls in more than a dozen places. How can I reuse a single AsynchTask class for all these calls as my call to the ne开发者_如何学运维twork is from different Activity?
This made me rewrite the AsyncTask wherever in the Activities there is a network call.
Without knowing the full details of your code it does sound to me as though you might be using AsyncTask in a way it was never intended.
From the docs:
This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
In my mind AsyncTask is suitable for relatively simple asynchronous tasks such as single file download/stream etc. Once there is a need for more complicated asynchronous tasks then perhaps utilising the full functionality of Threads is called for. It all comes down to design and correct choice of available tool for the task...
It really all depends how involved your network calls are. If they are quick and you're not pulling a lot of data, then the AsyncTask will be fine.
Ultimately, what you need to do is clean up you code and make sure you're not repeating any logic. Make sure you're putting all the repeated logic in a single method.
So that you're not rewriting the AsyncTask for each Activity, make a "parent" Activity class where you define you're AsyncTask (and any other repeated logic). Then have the activities that need to run your AsyncTask extend this Activity.
If, however, your network calls are somewhat involved, you're probably going to want to look into another way of doing it. You may want to define a Service and bind all of your Activities to that service.
精彩评论